Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

upload an image using Trait in Laravel 9

How to upload an image using Trait in Laravel 9?

In this tutorial, I will give you an example of “How to upload an image using Trait in Laravel 9”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9, application.

First, what we’re doing here, This is the example :

image upload using trait in laravel
image store using trait in laravel

Traits in Laravel

As we know OOPs (Object-Oriented Programming Systems) concept and in that we have seen abstract classes and interfaces. A “Trait” is similar to an abstract class, in that it cannot be instantiated on its own but contains methods that can be used in a concrete class.

Traits are a mechanism for code reusability in single inheritance languages such as PHP.

In this example, we upload an image using Trait in the Laravel 9 application.

Recommended article: How to use Traits in Laravel.

Generating Migration with Model :

php artisan make:model Student -m

Migration Structure :

<?php

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('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

Run Migration :

php artisan migrate
student table migration

app\Models\Student.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
}

Create a Controller :

php artisan make:controller StudentController

routes\web.php :

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::view('/add-student','student.create');
Route::post('/store-student',[StudentController::class,'storeStudent'])->name('store.student');

create a Trait

Create a folder under app\Http\Traits and then create your Trait under Trait Folder.

app\Http\Traits\ImageUpload.php

<?php 
namespace App\Http\Traits;
use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;

trait ImageUpload
{
    public function uploadImage(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
    {
        $name = !is_null($filename) ? $filename : Str::random(25);

        $file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);

        return $file;
    }
}

app\Http\Controllers\StudentController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Student;
use App\Http\Traits\ImageUpload;

class StudentController extends Controller
{
    use ImageUpload;

    public function storeStudent(Request $request)
    {
     
      $student = new Student();
       
      if ($request->has('stu_image')) 
      {
        $image = $request->file('stu_image');
        $name = Str::slug($request->input('name')) . '_' . time();
        $folder = '/uploads/student/';
        $filePath = $folder . $name . '.' . $image->getClientOriginalExtension();
        $this->uploadImage($image, $folder, 'public', $name);
        $student->image = $name . '.' . $image->getClientOriginalExtension();
        }
        
        $student->name = $request->name;
        $student->email = $request->email;
        $student->save();
    }
}

resources\views\student\create.blade.php :

 <div class="container">
   <div class="row justify-content-center">
      <div class="col-lg-8">
      <div class="main">
      <h3>Image using Trait in Laravel 9 Example</h3>
      <form action="{{ route('store.student') }}" method="post" enctype="multipart/form-data">
         @csrf
         <div class="form-group">
            <label for="Name">Name<span class="text-danger">*</span></label>
            <input type="text" name="name" class="form-control" required>
         </div>
         <div class="form-group">
            <label for="Email">Email<span class="text-danger">*</span></label>
            <input type="text" name="email" class="form-control" required>
         </div>
         <div class="form-group">
            <label for="Image">Image<span class="text-danger">*</span></label><br>
            <input type="file" name="stu_image" accept="image/*" required>
         </div>
         <div class="form-group">
            <button type="submit" class="btn btn btn-primary">save student</button>
         </div>
      </form>
      </div>
      </div>
   </div>
</div>

Run Application:

http://127.0.0.1:8000/add-student

Output:

add student blade file
upload an image using Trait in laravel
image store in a folder using trait in laravel

Also Read:  How to Use Service Class In Laravel.