failed to load image from storage laravel 8 API in flutter

Viewed 41

i'm using laravel 8 & laravel 3.3.1

and i've had problem with my code on flutter right now..

the error is :

════════ Exception caught by image resource service ════════════════════════════

HTTP request failed, statusCode: 404, https://urlAPI/storage/products/1663071858.png ════════════════════════════════════════════════════════════════

and this is my Controller.php

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function saveImage($image, $path = 'public')
    {
        if(!$image)
        {
            return null;
        }

        $filename = time().'.png';
        Storage::disk($path)->put($filename, base64_decode($image));

        return URL::to('/').'/storage/'.$path.'/'.$filename;
    }
}

and this my ProductController.php

use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response([
            'product' => Product::orderBy('created_at', 'desc')->with('user:id,name,image')->withCount('comments', 'likes')
            ->with('likes', function($like){
                return $like->where('user_id', auth()->user()->id)->select('id', 'user_id', 'product_id')->get();
            })
            ->get()
        ], 200);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $attrs = $request->validate([
            'name'          => 'required|string',
            'price'         => 'required|string',
            'stock'         => 'required|string',
            'description'   => 'required|string',
            'type'          => 'required|string'
        ]);

        $image = $this->saveImage($request->image, 'products');

        $product = Product::create([
            'user_id'       => auth()->user()->id,
            'name'          => $attrs['name'],
            'price'         => $attrs['price'],
            'stock'         => $attrs['stock'],
            'description'   => $attrs['description'],
            'type'          => $attrs['type'],
            'image'         => $image
        ]);

        return response([
            'message' => 'Product created.',
            'product' => $product
        ], 200);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return response([
            'product' => Product::where('id', $id)->withCount('comments', 'likes')->get()
        ], 200);
    }
}

and this list_product.dart :

class HomePopularList extends StatefulWidget {
  const HomePopularList({Key? key}) : super(key: key);

  @override
  State<HomePopularList> createState() => _HomePopularListState();
}

class _HomePopularListState extends State<HomePopularList> {
  bool loading = true;
  int userid = 0;
  List<dynamic> _productList = [];

  @override
  void initState() {
    super.initState();
    retrieveProducts();
  }

  Future<void> retrieveProducts() async {
    userid = await getUserId();
    ApiResponse response = await getProducts();

    if (response.error == null) {
      setState(() {
        _productList = response.data as List<dynamic>;
        loading = loading ? !loading : loading;
      });
    } else if (response.error == unauthorized) {
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (context) => SignInScreen()),
          (route) => false);
    } else {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text('${response.error}')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      sliver: SliverGrid(
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 200.0,
          mainAxisSpacing: 3,
          crossAxisSpacing: 3,
          childAspectRatio: .7,
        ),
        delegate: SliverChildBuilderDelegate(
          (ctx, i) {
            Product product = _productList[i];
            return GestureDetector(
              onTap: () => Navigator.of(context).push(
                MaterialPageRoute(
                  builder: ((context) => DetailScreen(
                        popularModel: popularList[i],
                      )),
                ),
              ),
              child: Card(
                elevation: .7,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: ClipPath(
                        clipper: MyClipper(),
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: const BorderRadius.only(
                              topLeft: Radius.circular(10),
                              topRight: Radius.circular(10),
                            ),
                            image: product.image != null ? DecorationImage(
                              image: NetworkImage('${product.image}'),
                              fit: BoxFit.cover,
                            ) : null,
                          ),
                        ),
                      ),
                    ),

may someone help me, please? because i'm new on flutter language.. thanks for attention!

1 Answers

You just modify your storage function like below and check agian.

Storage::disk('public')->put($path .'/'. $filename, base64_decode($image));

Related