Concept of Trait in Laravel 9 Tutorial with Example

Reading Time: 9 minutes
4,317 Views

In general, Traits are nothing but a reusable collection of methods and functions that can be incorporated in any other classes. If you are looking for an article which gives you the complete idea about Trait class in Laravel 9.

Inside this article we will see the concept of Trait in Laravel 9 with Example. How to create & use it in Laravel 9 application, all basic things we will cover in this trait tutorial of laravel 9.

This tutorial will create a Trait class in laravel i.e reusable block of code, which we can be accessible inside any controller and can use it.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

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

Create Migration

We will create products & blogs table using migrations and then we seed test data inside it.

Open project into terminal and run these commands to create migration files.

$ php artisan make:migration create_products_table

$ php artisan make:migration create_blogs_table

It will create 2022_04_17_031027_create_products_table.php & 2022_04_17_031047_create_blogs_table.php files inside /database/migrations folder.

Open migration file 2022_04_17_031027_create_products_table.php and write this following code into it.

The code is all about for the schema of products table.

<?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('products', function (Blueprint $table) {
            $table->id();
            $table->string("name", 70);
            $table->string("slug", 100);
            $table->text("description");
        });
    }

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

Open migration file 2022_04_17_031047_create_blogs_table.php and write this following code into it.

The code is all about for the schema of blogs table.

<?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('blogs', function (Blueprint $table) {
            $table->id();
            $table->string("title", 60);
            $table->text("description");
        });
    }

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

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create products and blogs tables inside database.

Create Model

Back to project terminal and run these commands to create models.

$ php artisan make:model Product

$ php artisan make:model Blog

It will create Product.php & Blog.php files inside /app/Models folder. This file will help when we generate data using factory and insert into table.

Open Product.php and write this code into it.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    public $timestamps = false;
}

Open Blog.php and write this code into it.

<?php

namespace App\Models;

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

class Blog extends Model
{
    use HasFactory;

    public $timestamps = false;
}

Create Data Factory

Next,

Copy these commands and run into terminal to create factory files.

$ php artisan make:factory ProductFactory

$ php artisan make:factory BlogFactory

It will create files ProductFactory.php and BlogFactory.php inside /database/factories folder.

Open ProductFactory.php file and write this following code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Product>
 */
class ProductFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'description' => $this->faker->text,
        ];
    }
}

Open BlogFactory.php file and write this following code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Blog>
 */
class BlogFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'description' => $this->faker->text,
        ];
    }
}

Call Model Factory

Open DatabaseSeeder.php from /database/seeders folder. Load models and factories.

<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
         \App\Models\Product::factory(100)->create();

         \App\Models\Blog::factory(100)->create();
    }
}

Concept

\App\Models\Product::factory(100)->create();

\App\Models\Blog::factory(100)->create();

It will generate 100 fake rows for products and blogs table.

Run Data Seeder

Back to project terminal and run this command to run factory to seed fake data.

$ php artisan db:seed

It will generate and save fake data into products and blogs table.

Table: products

Table: blogs

Create Traits in Laravel

Create Traits folder inside /app/Http folder.

Next

Create DataTrait.php file inside /app/Http/Traits folder.

Open DataTrait.php and write this code into it.

<?php

namespace App\Http\Traits;

trait DataTrait
{
    public function getData($model)
    {
        // Fetch all the data according to model
        return $model::all();
    }
}

Here, we have created a simple trait method. This method returns all data on the basis of model what we will pass into it.

Create Controller

Open project into terminal and run this command into it.

$ php artisan make:controller DataController

It will create DataController.php file inside /app/Http/Controllers folder. Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

use App\Http\Traits\DataTrait;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Blog;

class DataController extends Controller
{
    use DataTrait;

    public function listProducts()
    {
        // Get data using Trait method
        $products = $this->getData(new Product());

        echo "<pre>";
        print_r($products);
    }

    public function listBlogs()
    {
        // Get data using Trait method
        $blogs = $this->getData(new Blog());

        echo "<pre>";
        print_r($blogs);
    }
}

As we can see, Single Trait method is usable in all methods.

Add Routes

Open web.php file from /routes folder. Add these routes into it.

//...

use App\Http\Controllers\DataController;

// Route to get all products
Route::get("list-products", [DataController::class, "listProducts"]);
// Route to get all blogs
Route::get("list-blogs", [DataController::class, "listBlogs"]);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Product URL – http://127.0.0.1:8000/list-products

Blog URL – http://127.0.0.1:8000/list-blogs

Here, we are only displaying all data into raw format. If you want then you can show it into view file as well.

We hope this article helped you to learn about Concept of Trait in Laravel 9 Tutorial with Example in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.