How to upload image to mysql via laravel?

Member

by domenico , in category: PHP Frameworks , 4 months ago

How to upload image to mysql via laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a month ago

@domenico 

To upload an image to a MySQL database using Laravel, you can follow these steps:


Step 1: Set up the database table First, make sure you have a table in your database to store the image. You can create a table with a column for the image like this:

1
2
3
4
5
Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('path');
});


Step 2: Create a form to upload the image Create a form in your view file to allow users to upload an image. Make sure the form includes the enctype attribute to support file uploads:

1
2
3
4
5
<form action="{{ route('uploadImage') }}" method="post" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image">
    <button type="submit">Upload Image</button>
</form>


Step 3: Create a route and controller method to handle the upload Create a route in your routes/web.php file that points to a controller method to handle the image upload:

1
Route::post('/uploadImage', 'ImageController@uploadImage')->name('uploadImage');


In your controller, you can define the uploadImage method to handle the image upload, store the image in the database, and save it to a folder on the server:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use AppModelsImage;

public function uploadImage(Request $request)
{
    $image = $request->file('image');
    
    $imageName = $image->getClientOriginalName();
    $image->move(public_path('images'), $imageName);

    $image = new Image;
    $image->name = $imageName;
    $image->path = 'images/' . $imageName;
    $image->save();

    return redirect()->back();
}


Step 4: Display the uploaded image To display the uploaded image, you can retrieve the image from the database and display it in your view file:

1
<img src="{{ asset($image->path) }}" alt="Uploaded Image">


That's it! You have now uploaded an image to a MySQL database using Laravel.