How to Create Reusable Code with Laravel 9 Traits

How to create reusable code in Laravel application? Well, if you are looking for this answer all over the internet like a nomad, then this Laravel Traits example tutorial will tell you profoundly how to use traits in Laravel to generate reusable code.

As per Laravel official documentation:

Traits class is a reusable code paradigm in Laravel that allows you to define a single inheritance logic for a reusable purpose recklessly.

You can assimilate traits in multiple self-dependent classes to evoke its power and for self-use.

Laravel 9 Traits Tutorial Overview

Laravel Traits tutorial overview, we will start with creating a brand new laravel app.

Understand how to evoke database connection by defining db values in the env config file, generating and confining model and migrations, creating test data, and injecting in the database with a faker factory.

Build traits to populate reusable code in laravel, use traits in laravel, and that too step by step.

Create Laravel Project

Use php artisan command to generate a new laravel project:

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

Add Database Details in ENV

Open .env configuration file equally important define your database configurations carefully:

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

Create Model and Run Migrations

To create a table into the database, generate a new Modal:

php artisan make:model Product -m

Open database/migrations/xxx_products_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 CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('description');            
            $table->timestamps();
        });
    }

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

Put below code in app/Models/Product.php:

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
    public $fillable = [
        'name',
        'description',
    ];
}

Use command to run migration:

php artisan migrate

Create Test Data

Add product table’s value in database/seeds/DatabaseSeeder.php file, it will generate dummy data in database.

<?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();

    	foreach (range(1,12) as $index) {
            DB::table('products')->insert([
                'name' => $faker->name,
                'description' => $faker->text
            ]);
        }
    }
}

Let’s seed database with test records:

php artisan db:seed

Create Laravel Traits File & Folder

First create Traits folder inside app/Http/ directory, secondly create ProductTrait.php file within the Traits folder:

Altogether, you need to place the below code in app/Http/Traits/ProductTrait.php file:

<?php

namespace App\Http\Traits;
use App\Models\Product;

trait ProductTrait {

    public function index() {
        $product = Product::all();
        return view('welcome')->with(compact('product'));
    }

}

Using Reusable Code with Laravel Traits

This step explains how you can use the laravel traits code reusing, so first you have to generate a new controller where you will take help of laravel traits to fetch the data from the database.

php artisan make:controller ProductController

Place code in app/Http/Controllers/ProductController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Traits\ProductTrait;

class ProductController extends Controller
{
    use ProductTrait;
}

In next step, you have to create route which will show and handle HTTP request, so add the below code in routes/web.php:

<?php

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


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

Route::resource('/product', ProductController::class);

Lastly, place the below code in resources/views/welcome.blade.php view file to display the data in tabular form with the help of Laravel Traits:

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

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

<body>
    <div class="container mt-4">
        <table class="table table-primary">
            <thead>
                <tr>
                    <th>#Id</th>
                    <th>Name</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                @foreach($product as $item)
                <tr>
                    <td>{{$item->id}}</td>
                    <td>{{$item->name}}</td>
                    <td>{{$item->description}}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</body>

</html>

Use below command to start the project:

php artisan serve
http://127.0.0.1:8000/product

The Laravel traits tutorial is over; this tutorial helped you learn how to create reusable code with Traits’ help and how to use laravel traits easily.