Laravel 9 Traits Example

Bayram EKER
3 min readAug 19, 2022

💡Did you know you can write abstract methods in a trait?

What is Traits

As we know OOPs (Object-Oriented Programming systems) concept and in that we have seen abstract classes and interfaces. A “Trait” is similar to an abstract class, in that it cannot be instantiated on its own but contains methods that can be used in a concrete class.

Traits are a mechanism for code reusability in single inheritance languages such as PHP.

Simply put, traits allow you to create desirable methods in a class setting, using the trait keyword. You can then inherit this class through the use keyword.

Step 1: 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

Step 2: Configure Database Connection

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

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

Step 3: Model and Migrations

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

php artisan make:model User -m

Open the database/migrations/timestamp_user_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 CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create(‘Users’, function (Blueprint $table) {
$table->id();
$table->string(‘name’);
$table->string(‘email’)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists(‘Users’);
}
}

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

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
public $fillable = [
‘name’,
‘email’,
];
}

The given below command heralds the migration execution.

php artisan migrate

Step 4: Create Traits in Laravel

Create Traits folder in app/Http, then create Traits/UserTrait.php file, then place the entire code in app/Http/Traits/UserTrait.php:

app/Traits/UserTrait.php

<?phpnamespace App\Traits;use App\Models\User;trait UserTrait {public function index() {// Fetch all the users from the 'users' table.$users = User::all();return view('users')->with(compact('users'));}}

Step 5: Add Route

first of all, we will create a resource route to show users using traits in laravel 8 . so let’s add simple routes like bellow:

routes/web.php

use App\Http\Controllers\UserController;Route::resource('users', UserController::class);

Step 6: Create Controller

Here, we will create a new controller as UserController. so let’s add the below code on that controller file.

app\Http\Controllers\UserController

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Traits\UserTrait;class UserController extends Controller{use UserTrait;}

Step 7: Create a View file

here, we need to create a blade file and in this blade file, we use users and use their code.

resources/views/users.blade.php

<!DOCTYPE html><html><head><title>Laravel Trait Example</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" /></head><body><div class="container"><div class="row mt-5"><div class="col-10 offset-1 mt-5"><div class="card"><div class="card-header bg-info"><h3 class="text-white">Laravel Trait Example</h3></div><div class="card-body"><table class="table table-bordered"><tr><th>No.</th><th>Name</th><th>Email</th></tr>@forelse($users as $key => $user)<tr><td>{{ ++$key }}</td><td>{{ $user->name }}</td><td>{{ $user->email }}</td></tr>@empty<tr><td colspan="3">No Users Found</td></tr>@endforelse</table></div></div></div></div></div></body></html>

Step 8: Create Dummy Records:

Here, we need to add some dummy records on the user’s table using factory So let’s open the terminal and run bellow artisan tinker command:

php artisan tinkerUser::factory()->count(100)->create()

Step 9: Run Your Project

Now we are ready to run our example so run the bellow command for a quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/users

It will help you…..

--

--