Concept of Trait in Laravel 8 Tutorial with Example

Share this Article

In general, Traits are nothing but a reusable collection of methods and functions that can be incorporated in any other classes.

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

What we will do inside this article –

  • Create a Trait in laravel i.e reusable block of code, which we can access in any controller and use it.

Let’s get started.


Installation of Laravel 8 Application

Laravel Installation can be done in two ways.

  • Laravel Installer
  • By using composer

Laravel Installer

To install Laravel via Laravel installer, we need to install it’s installer first. We need to make use of composer for that.

$ composer global require laravel/installer

This command will install laravel installer at system. This installation is at global scope, so you type command from any directory at terminal. To verify type the given command –

$ laravel

This command will open a command palette of Laravel Installer.

To create ad install laravel project in system,

$ laravel new blog

With the name of blog a laravel project will be created at your specified path.

By using composer

Alternatively, we can also install Laravel by Composer command create-project. If your system doesn’t has Composer Installed, Click here to Install Composer ? Here is the complete command to create a laravel project-

$ composer create-project --prefer-dist laravel/laravel blog

After following these steps we can install a Laravel 8 application into system. To start the development server of Laravel –

$ php artisan serve

This command outputs –

Starting Laravel development server: http://127.0.0.1:8000

Assuming laravel 8 already installed at 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

To create a table in database, we will use migration command of laravel artisan to create schema. Open project into terminal and run these artisan commands.

$ php artisan make:migration CreateProductsTable

$ php artisan make:migration CreateBlogsTable

It will create migration files with name 2021_03_18_182916_create_products_table.php & 2021_03_18_182928_create_blogs_table.php according to my timestamp values at location /database/migrations.

Open migration file 2021_03_18_182916_create_products_table.php and write this code into it.

<?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", 70);
            $table->string("slug", 100);
            $table->text("description");
        });
    }

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

Open migration file 2021_03_18_182928_create_blogs_table.php and write this code into it.

<?php

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

class CreateBlogsTable 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');
    }
}

Migrate Migration

To run migration file and create table.

$ php artisan migrate

This command will create database tables.


Create Model

To create model, run this artisan command.

$ php artisan make:model Product

$ php artisan make:model Blog

It will create files with name Product.php & Blog.php at location /app/Models.

Open Product.php and write this code.

<?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 Factory File – Data Seed

To seed dummy data into table, we need a factory file. To create factory file we will use artisan command. Back to terminal and run these artisan commands.

$ php artisan make:factory ProductFactory --model=Product

$ php artisan make:factory BlogFactory --model=Blog

It will create files with name ProductFactory.php & BlogFactory.php at location /database/factories.

Open ProductFactory.php and write this code into it.

<?php

namespace Database\Factories;

use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class ProductFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Product::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'slug' => Str::slug($this->faker->name),
            'description' => $this->faker->text,
        ];
    }
}

Open BlogFactory.php and write this code into it.

<?php

namespace Database\Factories;

use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class BlogFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Blog::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->name,
            'description' => $this->faker->text,
        ];
    }
}

Run Factory File

To run this factory which results, it creates dummy data into database table. We will run this factory file by Tinker Shell panel

$ php artisan tinker

It will open a shell interface, by the help of which we will interact with database.

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

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

Above commands will create 100 dummy rows for Product table and 100 rows for Blog table.


Create Traits in Laravel

Create Traits folder in /app/Http, then create DataTrait.php file at /app/Http/Traits file.

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, which returns all data on the basis of model what we will pass into it.


Create Routes

Open web.php from /routes folder.

// At header
use App\Http\Controllers\DataController;

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

Create Controller

To create controller, run this artisan command.

$ php artisan make:controller DataController

It will create a file with name DataController.php at /app/Http/Controllers folder.

Open DataController.php 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 now used to methods. even we can use the sample in any controller where we want data.


Application Testing

Open project to terminal and type the command 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 8 Tutorial with Example in a very detailed way.

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.

Find More on Laravel 8 Articles here

Leave a Comment

What are CSRF Functions in CodeIgniter 4 Tutorial
MySQL Stored Procedure in CodeIgniter 4 Tutorial