Laravel 9 Traits Example: How to Create and Use Trait in Laravel

Laravel Traits Example; Today in this tutorial we will show hyou how to create Trait in Laravel, and how to use Trait in the Laravel application.

A Trait is simply a group of methods that you want to include within another class. Traits allow us to develop a reusable piece of code and inject it in controller and modal in a Laravel application. Let’s see how can you create a trait and how to use in laravel controller or model.

About Traits: Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.

Simply follow the following steps to create and use trait class in laravel application.

Step 1: Create a Trait

Think you are storing post details in database and you have a column slug and you want the slug generated from Trait file, How is this post? Let’s create a folder “Traits” inside “app” directory then create “PostTrait.php” file, Your path look like below. Now open your file and add below code on it.

We have created two function on it, one is generateSlug and another is “getTestExample”, How we get that data in our controller check the controller now.

app\Traits\PostTrait.php

<?php

namespace App\Traits;

trait PostTrait
{
    public function generateSlug($string)
    {
        return strtolower(preg_replace(
            ['/[^\w\s]+/', '/\s+/'],
            ['', '-'],
            $string
        ));
    }

    public function getTestExample()
    {
        return 'This is test trait example.';
    }
}

Step 2: Use Trait in Controller

Now we use the Trait file in our controller just like below. We have show the use trait class and their function as well with comments.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use App\Traits\PostTrait; // use the post trait here

class PostController extends Controller
{
    use PostTrait; // here we use inside class
    public function index()
    {

        $exampleTrait = $this->getTestExample(); // Here we use the getTestExample trait
        dd($exampleTrait);
        $products = Product::all();

        return view('product.index', compact('products'));
    }

    public function store(Request $request)
    {
        $slug = $post->generateSlug($request->title); // here we use the generateSlug trait
        $post = Post::([
            'title' => $request->title,
            'description' => $request->description,
            'slug' => $slug
        ]);

        dd($slug);
        dd($post);
        return redirect()->route('posts.index')->with('success','Product created successfully.');
    }
}

Note: We can use the traits in our model as well just like controller.

Now create a new post check the generated slug comes in your controller store function where we already added dd.

I hope you enjoy with this article.. feel free to follow us for more new updates.

Leave a Comment