Hello Artisan,
In this post, I will give you an example of laravel 9 image upload example. I will explain simply step-by-step image upload in laravel 9. So this image upload example will help you to learn how to upload images in laravel 9 to the database.
I will simply create a custom trait to upload image in Laravel 9. I will create two routes, one is get to show the image upload form and the other is a post request route for uploading image in Laravel 9 from the controller.
I will use the User
model to upload image. So you have to follow the following steps and get an image upload in the laravel 9 application. So let's see the how to upload image in Laravel 9.
Step 1: Download Laravel 9
To upload an image in Laravel 9, you need to download a fresh Laravel application. So download it by the following command:
composer create-project laravel/laravel example-app
Step 2: Create Model & Migration
In this step, we need a table cause we are going to save image in our database in Laravel 9. So create model and update it like below:
app\Models\User.php
namespace App\Models;
use App\Helper\Imageable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, Imageable;
protected $fillable = [
'name',
'email',
'password',
'image'
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function storeUser($request)
{
$this->name = $request->name;
$this->email = $request->email;
$this->password = bcrypt($request->password);
$this->save();
return $this;
}
}
Now update the migrations file like below:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('image')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
Now run php artisan migrate
command to update the database.
Step 3: Create Imageable Trait
Now in this step, we need to create a imageable
trait to upload image in Laravel 9 application. So create it in the following path.
app\Helper\Imageable.php
namespace App\Helper;
Trait Imageable
{
public function storeMedia($request)
{
$path = public_path('tmp/uploads');
if ( ! file_exists($path) ) {
mkdir($path, 0777, true);
}
$file = $request->file('image');
$fileName = uniqid() . '_' . trim($file->getClientOriginalName());
$this->image = $fileName;
$this->save();
$file->move($path, $fileName);
return $this;
}
}
Step 4: Create routes
Now in this step, open the routes/web.php
file and add the routes to manage GET and POST requests for render view and store image logic.
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function () {
Route::get('/', 'create')->name('user.create');
Route::post('/', 'store')->name('user.store');
});
Step 5: Create Controller
In this step, we will create a new UserController; in this file, we will add two methods create()
and store()
for render view and store image logic.
app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Http\Requests\ImageUploadRequest;
use App\Models\User;
use Illuminate\Support\Facades\Blade;
class UserController extends Controller
{
public function create()
{
return Blade::render('welcome');
}
public function store(ImageUploadRequest $request, User $user)
{
$user->storeUser($request)->storeMedia($request);
return 'Image uploaded successfully';
}
}
Step 6: Create Form Validation Request
In this step, we have to validate our image request before saving it into the database. To create a request, run by the following command
php artisan make:request ImageUploadRequest
Read also: Create Custom Trait to Resize and Upload Image in Laravel
Now update this ImageUploadRequest like below:
App\Http\Requests\ImageUploadRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImageUploadRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
];
}
}
Step 7: Create Blade File
At the last step, we need to create welcome.blade.php
file and in this file we will create a form with a file input button.
resources/views/welcome.blade.php
Recommended: Laravel 8 Upload Image to Storage Folder Example
Hope this Laravel 9 image upload tutorial will help you.
#laravel #laravel-9x #image-upload