Reputation: 1
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!
Upvotes: 0
Views: 907
Reputation: 31
In my case since he used protected $fillable in Models. I added logo this resolved my issue. See the code below.
protected $fillable = ['title', 'logo','company', 'location', 'website', 'email', 'description', 'tags'];
Upvotes: 3
Reputation: 19
What Eric commented worked for me as well, in the Models file under Http, you have to add whatever name that you used for the logo ('logo', 'image', 'picture' etc.), since in the course he uses protected $fillable.
Upvotes: 2
Reputation: 3
Are you using "protected $fillable =..." in your model file? If so, you need to add 'logo' to the array.
(I'm doing the course and got stuck at the same part.)
Upvotes: 0
Reputation: 1392
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/
Upvotes: 0
Reputation: 64
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.
Upvotes: 0