Create and Use Traits in Laravel 8 - Step by step guide ?

Create and Use Traits in Laravel 8 - Step by step guide ?

Traits offer you the freedom to reuse a block of code; the whole idea of Traits is derived from PHP. The entire pattern is to reduce single inheritance limitation by allowing a web developer to reuse the sets of functions and methods in various or non-dependent classes existing in a distinct class.
Here at Fixwebnode, as part of our Website Development Services, we regularly help our Customers to perform related Laravel Application queries.
In this context, we shall look into how to create Traits in the Laravel 8 application.



Steps to create Traits in Laravel

1. Create a new Laravel Application
You need to install the Laravel app, so execute the command to download the app via command-line-tool:


$ composer create-project laravel/laravel laravel-traits-sample --prefer-dist


Then, Move into the project directory:


$ cd laravel-traits-sample




2. Configure Database
Database configuration is easy to implement in Laravel; you can store and perform create, read, update, and delete operation quickly.
Please copy the below code and paste in the .env file; it makes the concurrent connection between laravel and MySQL database:


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




3. Create Model
Now, Run the command to create a Sample model; it holds the values that interact with the database:


$ php artisan make:model Sample -m


Place the following code in database/migrations/timestamp_samples_table.php:


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

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

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


Next, run the migration to propel the model values in the database:


$ php artisan migrate




4. Generate Fake Data
To see traits in action within laravel, we have to add dummy data in the database. To accomplish this task, we are using the Faker service.
Place the code in the database/seeds/DatabaseSeeder.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,15) as $index) {
DB::table('students')->insert([
'name' => $faker->name($gender),
'email' => $faker->email
]);
}
}
}


Next, we can create dummy data. All it needs just a single line of command:


$ php artisan db:seed




5. Make Trait in Laravel 8
Creating the Traits folder also create SampleTrait.php within the same folder. As you can see within the index() method, we are getting Employee records and injecting in the laravel view:


namespace App\Http\Traits;
use App\Sample;

trait SampleTrait {
public function index() {
$sample = Sample::all();
return view('home')->with(compact('sample'));
}
}




6. Use Laravel Traits
In order to inject the Laravel Trait, simply run the below command to generate a new controller:
php artisan make:controller SampleController
Then, Place the code in Http/Controllers/SampleController.php:


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

class SampleController extends Controller
{
use SampleTrait;
}




7. Create Route
Include the code in routes/web.php:


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

Route::resource('samples', 'SampleController');


Finally, we have to create the view and add the code in resources/views/home.blade.php:


@foreach($sample as $item)
{{$item->id}}{{$item->name}}{{$item->email}}
@endforeach


 

How to test the Laravel Application for Traits ?

You need to run the app in the browser to check the Laravel Traits example that we have built so far:


$ php artisan serve


Here is the URL that you have to put on the web browser's address bar:


http://127.0.0.1:8000/samples




[Need assistance in fixing Laravel PHP website issues ? We can help you. ]


Conclusion

This article covers how to create traits in Laravel 8 application. In fact, Traits allow us to develop a reusable piece of code and inject it in controller and modal in a Laravel application. 

Here at Fixwebnode, as part of our Website Development Services, we regularly help our Customers to perform related Laravel Application queries.


icon

Sign up to our Newsletter

...and get one free support ticket.