For the past few days I've been cool with Laravel until I just hit this very annoying issue. What I am trying to do is insert a file name into the database as well as upload the file to a specified directory in my public folder. I have searched so many topics on SO to no avail.
Here's my code:
public function store(Request $request) {
$request->validate([
'photo' => 'image|mimes:jpeg,png,gif,jpg|max:100|required',
'name' => 'required',
'email' => 'required|email',
'phone' => 'required'
]);
$student = new Student();
$file = $request->file('photo');
$ext = $file->extension();
$final_name = date("YmdHis")."newphoto".".".$ext;
$destinationPath= public_path('uploads/');
#dd(public_path('uploads'));
$file->move($destinationPath, $final_name);
$student->name = $request->name;
$student->email = $request->email;
$student->phone = $request->phone;
$student->photo = $final_name;
$student->save();
}
The file name gets inserted into the database but the file is not moved into the public/uploads directory as expected. Does anyone know why this is so? PS: I'm using Laravel 9. Any help will be much appreciated.
CodePudding user response:
Change your code to this
public function store(Request $request) {
$request->validate([
'photo' => 'image|mimes:jpeg,png,gif,jpg|max:100|required',
'name' => 'required',
'email' => 'required|email',
'phone' => 'required'
]);
$student = new Student();
$file = $request->file('photo');
$ext = $file->extension();
$final_name = date("YmdHis")."newphoto".".".$ext;
//$destinationPath= public_path('uploads/');
//dd(public_path('uploads'));
//$file->move($destinationPath, $final_name);
$file->storeAs('public/uploads', $final_name);
$student->name = $request->name;
$student->email = $request->email;
$student->phone = $request->phone;
$student->photo = $final_name;
$student->save();
}
Then run the artisan command
php artisan storage:link
PS. I have changed the answer. don't save uploaded files in public folder because it's publicly accessible. now your file will be saved in storage\app\public\uploads
If you have run the artisan command now you can access the uploaded files like this
{{ url('storage/uploads/'.$file_name) }}