Home > Enterprise >  Why the path of file image is not inserted into database MySQL in Laravel?
Why the path of file image is not inserted into database MySQL in Laravel?

Time:05-26

I'm learning Laravel right now on Laravel From Scratch 2022 by Traversy Media (Youtube). I want to create a file upload function for new listing form. When I tried to upload, the image was uploaded into the right path in public storage but the path is not in the database, instead the value inserted is 0.

Here is the code for ListingController.php

// Store Listing Data
    public function store(Request $request) {
        $formFields = $request->validate([
            'title' => 'required',
            'company' => ['required', Rule::unique('listings','company')],
            'location' => 'required',
            'website' => 'required',
            'email' => ['required', 'email'],
            'tags' => 'required',
            'description' => 'required'
        ]);

        $directory = "logos";

        if($request->hasFile('logo')) {
            $formFields['logo'] = $request->file('logo')->store('logos','public');
        }

        Listing::create($formFields); 


        return redirect('/')->with('message', 'Listing created successfully!');   
    }

Here is the screenshot of image that I successfully uploaded but the value in database is 0.

Screenshot of Laravel storage/app/public/logos directory

Screenshot of MySQL database, column logo is used to store image path

Thank you for your help!

CodePudding user response:

I tested it, and your code is fine. probably it might be related to the type of logo column in your database. make sure it's "Varchar" and not "Boolean".

you could use: var_dump($request->file('logo')->store('logos','public')); to see if the path of image showed up or not. if not, try use storeAs() instead of store() .

$request->file('logo')->storeAs('public' , "logo.jpg");

in this alternative code, you can set a proper name for your image as a second parameter and save it in the database.

CodePudding user response:

It seems $request->file('logo')->store('logos','public') doesn't return the file name or path. Considering that, it might be better to assign a custom file name. In the example below, we use the name of the original uploaded file.

$fileName = $request->file('logo')->getClientOriginalName();
$request->file('logo')->storeAs('logos', $fileName);
$formFields['logo'] = $fileName;

Source: https://blog.quickadminpanel.com/file-upload-in-laravel-the-ultimate-guide/

  • Related