php – Correctly upload image within a form to Laravel disk-ThrowExceptions

Exception or error:

I have a flutter form which contains both textual data and an image. I am using http package to send post request to the Laravel backend that has a route in api.php like:

Route::post('/locations', 'LocationController@store');

So at first since I have never tried to upload an image to laravel I had to disable my image input just to check if things were working and and I was successfully able to send a post request from my frontend with a status code of 201 Created with the record successfully created in the database. So I have added the first two lines below in my controller to save the image which are causing my requests to fail with 500 | server error. (The rest lines were already available and working with previous requests):

public function store(Request $request)
    $locationName = $request["name"];
    $data = base64_decode($request["image"]); // Image sent from flutter like: _image != null ? base64Encode(_image.readAsBytesSync()) : ''
    Storage::disk('public_images')->put("${$locationName}.jpg", $data); // public_images is defined below
    return location::create([
        'name' => $request["name"], 
        'time' => $request["time"],
        'package' => $request["package"],
        'summary' => $request["summary"],
        'info' => $request["info"],
        'image' => $request["image"]

I have defined the public_images disk(in config/filesystems.php) as follows: (I have to save in the public directory because my server doesn’t work with symlinks, but that isn’t my problem):

'public_images' => [
        'driver' => 'local',
        'root'   => public_path() . '/images',

Now What I want is to save the image to the disk and get the path to store it to the database table so that when accessing from flutter I will only use the api url along with that path to display the image as a network resource. So what is the right way to upload a file from flutter app to laravel backend? Or am I doing it all wrong?

Also: since I am new to file uploads in laravel from flutter, what generally are the best practices in uploading files to a laravel server? Thanks in advance!

How to solve:

You may want to check if request object has any file and the file is valid, then store the file in public directory and store the uri in db.

if($request->hasFile('image') && $request->file('image')->isValid()){
   $file = $request->file('image');
   $filePath = str_replace('public/', '', $file->storeAs('public/dir', 'name.' . $file->guessExtension()));

now with Laravel baseUrl helper you can generate the full path of stored file and using for loading, streaming or force to download.

Leave a Reply

Your email address will not be published. Required fields are marked *