How to Create Reusable Code with Laravel 8 Traits

In this tutorial you will learn about the How to Create Reusable Code with Laravel 8 Traits and its application with practical example.

In this How to Create Reusable Code with Laravel 8 Traits tutorial I will show you how to create reusable code in Laravel 8 application. In this tutorial you will learn to create laravel traits  to generate reusable code. In this article I will share example to create and use laravel traits

What Is Laravel Traits?

In laravel, traits is a independent reusable class that is that allows you to implement single inheritance in order to reuse it.

How to Create Reusable Code with Laravel 8 Traits

In this step by step tutorial I will demonstrate you with example how to create an use laravel traits.

Create Laravel Project

First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command

Setup Database Credentials

Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.

Create Model and Run Migrations

Now, in this step we will create model and migration file. Please run the following command:

Now, open database/migrations/xxx_products_table.php file and put the following code.


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


Now, in this step we will create model and migration file. Please run the following command:

Create Test Data

In this step we will add some test data in product table. Add product table’s value in database/seeds/DatabaseSeeder.php file, it will generate dummy data in database.

Let’s seed database with test records:

Create Laravel Traits File & Folder

Lets create a Traits folder inside app/Http/ directory, then create ProductTrait.php file within the Traits folder. Now, you need to place the following code in app/Http/Traits/ProductTrait.php file:

Using Reusable Code with Laravel Traits

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

Create Routes

After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.

routes/web.php

Create Blade Views

Now, 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:

Run Development Server

Now we are ready to run our example so lets start the development server using following artisan command –

Now, open the following URL in browser to see the output –

In this tutorial we have learn about the How to Create Reusable Code with Laravel 8 Traits and its application with practical example. I hope you will like this tutorial.