How To Upload An Image in Laravel 8

PREREQUISITES:
Have the following installed on the system you use:
- XAMPP (running)
- Composer
- Visual Studio Code (or any code editor with terminal)
What You Will Learn:
- Adding Images to your Database
- Handling Image Upload
- Fetching and Displaying Image
Getting Started
The first step is to create a Laravel form, I have an article on how to use Laravel Collective for forms here but you can either use blade components or HTML syntax it works fine.
Opening Form Tag
Laravel Collective:
{!!Form::open([‘action’ => ‘App\Http\Controllers\BookController@store’, ‘method’ => ‘post’, ‘enctype’ => ‘multipart/form-data’, ‘class’ => ‘container’]) !!}
HTML
<form action=”App\Http\Controllers\BookController@store”, method=”POST” enctype=”multipart/form-data”>
Explanation:
We open a form tag and the action is where we send the data, I suggest using a controller with a resource connected to your database, this article will help you set up easily, click here. It is important to add the enctype if you are using a form that has file upload and it can only be used if your method is set to POST.
Image Input
Laravel Collective
{!! Form::file(‘image’) !!}
HTML:
<input type=”file” name=”image” id=””>
Closing Tag
Laravel Collective:
{!! Form::close() !!}
Adding Images to your database:
Before we send images, let’s create a section in our database that would receive and store these images, we will create a migration and we can do this by running
php artisan make:migration add_image_to_table
Where I have written, “table” simply put the name of the table in your database, this makes a migration which you would find in the database folder in your Laravel app directory.
In the migration file locate the up function and paste this code:
Schema::table(‘books’, function (Blueprint $table) {
$table->string(‘image’);
});
And the in the down paste this code:
Schema::table(‘books’, function (Blueprint $table) {
$table->dropColumn(‘image’);
});
Then go ahead and run this in your terminal
php artisan migrate
If you use PHPMyAdmin to look at your table, you will notice that the column for the image has been added to your database table.
Validating Images
In your Controller(hopefully you created a controller resource, if not do that here) locate the store function, if you have a validation function and you want to add validation for your image so go ahead and use this:
‘image’ => ‘image|nullable|max: 1999’
This tells Laravel to make sure the file is an image, not necessary to upload, and cannot exceed 2 megabytes.
Handling File Upload
Still, in the store function, we want to set actions for if the user has uploaded the file or not, so we write the ubiquitous if statement, copy and paste the code below:
if ($request->hasFile(‘image’)) {
$filenameWithExt = $request->file(‘image’)->getClientOriginalName ();// Get Filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);// Get just Extension
$extension = $request->file(‘image’)->getClientOriginalExtension();// Filename To store
$fileNameToStore = $filename. ‘_’. time().’.’.$extension;\// Upload Image$path = $request->file(‘image’)->storeAs(‘public/image’, $fileNameToStore);
}// Else add a dummy image
else {
$fileNameToStore = ‘noimage.jpg’;
}
In the upload image query, we asked Laravel to store the image in our image folder in storage > app > public, but we usually reference images from our public folder, not storage folder, so run this command:
php artisan storage:link
This links the storage folder to the public folder
For image, I am using shoe image
In the store function where we created a variable for new table data add this line:
// Create New Data
…
$variable->image = $fileNameToStore;
…
}
Fetching and Displaying Image
In the index function of your controller, connect to your table and with table data return a blade template as a view i.e:
$var = Book::all();
return view(‘image’)->with(‘var’, $var);
My view here is image which means that in the resources > views directory I will create a file called image.blade.php and in there we will loop through the database to output images:
@if(count($table) > 0
@foreach($var as $vars) <div class=”col-md-6 d-flex align-items-center justify-content-center”>
<img src=”/storage/shoeimages/{{$var->image}}” alt=”” width=”100">
</div>
@endforeach
@else
<p>No Images </p>
@endif
I am using bootstrap but feel free to edit the styles how you like.
That’s all if you have any questions, the comment section is always open or you can send me a DM on Twitter