Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload an image using Laravel?

The problem:
I want to upload an image to a mySQL database using Laravel.

what I have tried:
I looked for other stack-overflow questions but they weren't helpful.

the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.

like image 275
Omar Avatar asked Oct 19 '25 22:10

Omar


1 Answers

First you need the form on your view (don't forget the csrf token):

<form action="/image-upload" method="POST" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image">
    <button type="submit">Upload</button>
</form>

And on your routes file add the route for POST method:

Route::post('image-upload', 'ImageUploadController@imageUploadPost');

Then on your Controller create the function that will validate and move your image to the 'public/images' folder.

public function imageUploadPost()
{
    request()->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $imageName = time().'.'.request()->image->getClientOriginalExtension();
    request()->image->move(public_path('images'), $imageName);
}

For better solution please read this: Laravel File Storage

like image 64
Denis Avatar answered Oct 22 '25 12:10

Denis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!