Laravel Traits | How to Create Trait in Laravel? (ok)

https://www.itsolutionstuff.com/post/laravel-traits-how-to-create-trait-in-laravelexample.html

Lấy một ví dụ khác để giải thích

C:\xampp\htdocs\reset\routes\web.php

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
/*
|--------------------------------------------------------------------------
| 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::get('/', function () {
    return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::resource('employees', EmployeeController::class);

C:\xampp\htdocs\reset\resources\views\test.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <title>Laravel Traits Tutorial with Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <table class="table">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                @foreach($employee as $item)
                <tr id="user{{$item->id}}">
                    <td>{{$item->id}}</td>
                    <td>{{$item->name}}</td>
                    <td>{{$item->email}}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</body>
</html>

C:\xampp\htdocs\reset\database\migrations\2022_05_20_090108_create_employees_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('employees', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('employees');
  }
}

C:\xampp\htdocs\reset\database\seeders\DatabaseSeeder.php

<?php
namespace Database\Seeders;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder {
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run() {
    // \App\Models\User::factory(10)->create();
    $faker  = Faker::create();
    $gender = $faker->randomElement(['male', 'female']);
    foreach (range(1, 15) as $index) {
      DB::table('employees')->insert([
        'name'  => $faker->name($gender),
        'email' => $faker->email,
      ]);
    }
  }
}

C:\xampp\htdocs\reset\app\Http\Traits\EmployeeTrait.php

<?php
namespace App\Http\Traits;
use App\Models\Employee;
trait EmployeeTrait {
  public function index() {
    $employee = Employee::all();
    return view('test')->with(compact('employee'));
  }
}

C:\xampp\htdocs\reset\app\Http\Controllers\EmployeeController.php

<?php
namespace App\Http\Controllers;
use App\Http\Traits\EmployeeTrait;
class EmployeeController extends Controller {
  use EmployeeTrait;
}

C:\xampp\htdocs\reset\app\Models\Employee.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model {
  use HasFactory;
}

Laravel Traits | How to Create Trait in Laravel?

By Hardik Savani February 20, 2020 Category : LaravelPauseUnmuteLoaded: 2.00%FullscreenVDO.AIToday, i will show you step by step how to make a trait in laravel application. you can easily create traits and use it in laravel controller and modal. i will give you simple example of creating traits in laravel example.

You can easily use php laravel traits in laravel 5 and laravel 6 application.

Traits is a simply a group of methods that you want include within another class. You can easily reuse that methods to another class. Trait is save to write same code again and again.

Here, i will give you very simple example how to create trait and how to use trait in laravel project. we will create one trait "ImageTrait". in that trait we will write code for image upload. So where ever we need upload image then we can use this ImageTrait trait. For example we have use profile, product picture etc, so we can use same trait method we don't require to write again and again same code.

I written few days ago image uploading with laravel 6. you can see that tutorial from here: Image Upload in Laravel 6. You can see on that post i written code for image upload. we can use trait for image upload on that example like as bellow example:

We need to create our custom trait as ImageTrait on new folder "Traits". we will create new trait with verifyAndUpload(). verifyAndUpload() helps to upload image from controller. So let's create bellow file and write code as like bellow code:

app/Traits/ImageTrait.php

<?php  namespace App\Traits;  use Illuminate\Http\Request;  trait ImageTrait {      /**     * @param Request $request     * @return $this|false|string     */    public function verifyAndUpload(Request $request, $fieldname = 'image', $directory = 'images' ) {          if( $request->hasFile( $fieldname ) ) {              if (!$request->file($fieldname)->isValid()) {                  flash('Invalid Image!')->error()->important();                  return redirect()->back()->withInput();              }              return $request->file($fieldname)->store($directory, 'public');          }          return null;      }  }

Now let's see bellow controller code, you can see how we can use this trait in our controller method. you can same use it again and again when you require to upload image.

So, let's write code as bellow for controller.

app/Http/Controllers/ItemController.php

Read Also: Laravel Disable Registration Route Example

<?php   namespace App\Http\Controllers;   use Illuminate\Http\Request;use App\Item;use App\Traits\ImageTrait;  class ItemController extends Controller{    use ImageTrait;     /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */    public function create()    {        return view('imageUpload');    }       /**     * Display a listing of the resource.     *     * @return \Illuminate\Http\Response     */    public function store(Request $request)    {        $input = $request->all();           $input['image'] = $this->verifyAndUpload($request, 'image', 'images');           Item::create($input);            return back()            ->with('success','record created successfully.');       }}

Now, you can use it in your other controller same trait.

I hope it can help you...

Last updated