How to Create and Use Traits in Laravel 9 Application

This tutorial walks you through on how to create Traits in the Laravel application. Also, we will look at how to use traits in Laravel.

Traits offer you the freedom to reuse a block of code; the whole idea of Traits is derived from PHP. The entire pattern is to reduce single inheritance limitation by allowing a web developer to reuse the sets of functions and methods in various or non-dependent classes existing in a distinct class.

Create Laravel Application

You need to install the Laravel app, so execute the command to download the app via command-line-tool.

composer create-project laravel/laravel laravel-traits-tutorial --prefer-dist

Move inside the project root:

cd laravel-traits-tutorial

Database Configuration

Database configuration is effortless in Laravel; you can store and perform create, read, update, and delete operation quickly.

Please copy the below code and paste in the .env file; it makes the concurrent connection between laravel and MySQL database.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Make Model

Execute the command to create an Employee model; it holds the values that interact with the database.

php artisan make:model Employee -m

Place the following code in database/migrations/timestamp_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');
    }
}

Next, run the migration to propel the model values in the database.

php artisan migrate

Generate Fake Data

To see traits in action within laravel, we have to add dummy data in the database. To accomplish this task, we are using the Faker service.

Place the code in the database/seeds/DatabaseSeeder.php.

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

        $gender = $faker->randomElement(['male', 'female']);

    	foreach (range(1,15) as $index) {
            DB::table('students')->insert([
                'name' => $faker->name($gender),
                'email' => $faker->email
            ]);
        }
    }
}

Next, we can create dummy data. All it needs just a single line of command:

php artisan db:seed

How to Make Trait in Laravel 9

Create the Traits folder also create EmployeeTrait.php within the same folder. As you can see within the index() method, we are getting Employee records and injecting in the laravel view.

<?php

namespace App\Http\Traits;
use App\Employee;

trait EmpoyeeTrait {
    public function index() {
        $employee = Employee::all();
        return view('home')->with(compact('employee'));
    }
}

Using Laravel Traits

Execute command to generate a new controller, in this controller we will inject the Laravel Trait.

php artisan make:controller EmployeeController

Place the code in Http/Controllers/EmployeeController.php.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Traits\EmployeeTrait;

class EmployeeController extends Controller
{
    use EmployeeTrait;
}

Creating Route

Include the code in routes/web.php.

Route::get('/', function () {
    return view('home');
});

Route::resource('employees', 'EmployeeController');

Finally, we have to create the view and add the code in resources/views/home.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>

Run Laravel App

You need to run the app in the browser to check the Laravel Traits example that we have built so far.

php artisan serve

Here is the URL that you have to put on the browser’s address bar.

http://127.0.0.1:8000/employees