Laravel 7|8 Traits Example: Create & Use Trait in Laravel

Last updated on by Digamber
Today is an auspicious day because we are going to learn about Laravel 7 Traits, how to create Trait in Laravel, and how to use Trait in the Laravel 7 application. Traits allow us to develop a reusable piece of code and inject it in controller and modal in a Laravel application.

I would like you to comprehend the entire process, respectively, with a basic app example. In this app, we will render student records from the database and display them on the frontend. I will take the holistic approach that helps you understand the Laravel Traits topic with persistence and help you comprehend the correct usage of Traits in Laravel.

What are Traits?

In general, Traits are nothing but a reusable collection of methods and functions that can be incorporated in any other classes. Let’s see what the exact memoir of Traits as per PHP.

“Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is designed to lessen some limitations of single inheritance by permitting a developer to reuse sets of methods unobstructedly in numerous independent classes living in distinct class hierarchies. The semantics of the combination of Traits and classes is determined in a way which decreases complexity and bypasses the usual difficulties connected with compound inheritance and Mixins.

A Trait is comparable to a class, although only designed to group functionality in a fine-grained and constant way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behaviour; that is, the application of class members without requiring inheritance.”

Laravel Traits Example

Please assimilate all the steps respectively and gradually to know the nitty-gritty of creating and using Traits in Laravel. Let us evoke our first step to get started.

Install New Laravel Application

Generically, i invoke my first step by installing the new laravel application. However, if you have done this task already, then you can skip it and directly move to the second step.

Run the command to start the project installation.

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

Right after the project installation, get inside the project directory.

cd laravel-traits-example

Configure Database Connection

Please insert the following code in .env file, and it evokes the connection between laravel and database with refined consensus.

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

Model and Migrations

We need to create the Student model so that we can set schema in the database. Run command to create the Student model.

php artisan make:model Student -m

Open database/migrations/timestamp_students_table.php file and incorporate the following code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

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

Open app/Student.php and insert the modal values in the $fillable array.

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    protected $fillable = [
        'name',
        'email',
    ];
}

The given below command heralds the migration execution.

php artisan migrate

Insert Fake Data

To fetch data from the database we must have some records, so we will insert dummy data using Faker.

Insert the following code inside the database/seeds/DatabaseSeeder.php file.

<?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,10) as $index) {
            DB::table('students')->insert([
                'name' => $faker->name($gender),
                'email' => $faker->email
            ]);
        }
    }
}

Execute following command to generate fake records in the database.

php artisan db:seed

Create Traits in Laravel

Go to app folder and create a Traits/StudentTrait.php folder and file, and assimilate all the following code inside of it.

We defined the index() method, it will render Student records fro the MySQL database and send it to view.

<?php

namespace App\Http\Traits;
use App\Student;

trait StudentTrait {
    public function index() {
        // Fetch all the students from the 'student' table.
        $student = Student::all();
        return view('welcome')->with(compact('student'));
    }
}

Using Traits in Laravel

We require to define the routes that will be connected with controller and display the student records, add the following code in routes/web.php file.

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

Route::resource('students', 'StudentController');

We have to evoke a new controller where we can assimilate the Traits, which will fetch all the records from the database.

Generate a new controller using the below command.

php artisan make:controller StudentController

Insert following code in app/Http/Controllers/StudentController.php file to set the newly created Trait.

<?php

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

class StudentController extends Controller
{
    use StudentTrait;
}

Finally, we have to display the data that we conjugated in the Laravel Traits. Insert the following code in resources/views/welcome.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <title>Laravel Traits Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5">
        <table class="table table-inverse">
            <thead>
                <tr>
                    <th>Student ID</th>
                    <th>Name</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
                @foreach($student as $data)
                <tr id="student{{$data->id}}">
                    <td>{{$data->id}}</td>
                    <td>{{$data->name}}</td>
                    <td>{{$data->email}}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</body>

</html>

Start Application

Run the following command to start the app.

php artisan serve

Afterward, open the following URL in the browser to test out the Laravel Traits Example.

http://127.0.0.1:8000/students

Here is the final output:

Laravel Traits Example

The Bottom Line

Eventually, we have completed the Laravel Traits tutorial with an example. I took a holistic approach and must have been able to make you understand more preciously about this topic.

I truly believe in your intensive efforts which you put into effect to understand this topic. I refrain from losing the impetus of making you understand this topic and, respectively, followed every step to assimilate the entire concept in your conscience.

If you liked this tutorial, then do show your love. Share this tutorial with others. I will be grateful to you. Lastly, if you want to check out the full code of this tutorial, download it from GitHub.

Have a good day for you, and keep coding!