How To Create Custom Trait and Use Trait In Laravel 11

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
How To Create Custom Trait and Use Trait In Laravel 11

Welcome To ITSolutionsGuides,


In this tutorial, We will how to create the custom trait in laravel 11 using the artisan command. Laravel traits are the better solution of the reusable code instead of using the repeated code in all the controller file. Traits enhance code modularity and encourage the DRY (Don't Repeat Yourself) principle. In this tutorial we will create a custom trait to modify the content and then return the modified content, this can be used in all the controller file with the use keyword and then use the custom trait,

php artisan make:trait {traitName}

To create custom traits and utilize them in Laravel 11, start by defining your trait with specific functionalities. Then, incorporate the trait into your classes using the "use" keyword. Ensure proper naming conventions and adhere to Laravel's coding standards for seamless integration and efficient code reuse.

Let's Create the Migration

Lets create the migration create migration using artisan command


database/migrations/2024_03_03_141714_create_posts_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('content');
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Let's Create Trait

Lets trait Sluggable using the following artisan command,
php artisan make:trait Traits/Sluggable
after creating the trait lets create the function to replace the spaces in the string using the '-' and then return the replaced string.


app/Traits/Sluggable.php

<?php
  
namespace App\Traits;
  
trait Sluggable
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function generateSlug($string)
    {
        $slug = strtolower(str_replace(' ', '-', $string));
        $count = 1;
  
        while ($this->slugExists($slug)) {
            $slug = strtolower(str_replace(' ', '-', $string)) . '-' . $count;
            $count++;
        }
  
        return $slug;
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected function slugExists($slug)
    {
        return static::where('slug', $slug)->exists();
    }
}

Let's Create Model

Lets use the custom trait we created by adding the trait in the model,
use App\Traits\Sluggable; and then use Sluggable;

then we will use the ->generateSlug() by passing the value that need to use the trait, here we created the trait to remove or replace the spaces in the string with the '-' while passing the data to the trait the trait will convert the string and then return the modified string.

App/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Model;
use App\Traits\Sluggable;
  
class Post extends Model
{
    use Sluggable;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    protected $fillable = ['title', 'content', 'slug'];
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function setTitleAttribute($value)
    {
        $this->attributes['title'] = $value;
        $this->attributes['slug'] = $this->generateSlug($value);
    }
}

Let's Create Route

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
    
Route::get('/post', [PostController::class, 'index']);

Let's Create Controller

Creating a controller lets create a PostController using the following artisan command,
php artisan make:controller PostController


app/Http/Controllers/PostController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request) {
          
        $post = Post::create([
            "title" => "Example Post",
            "content" => "This is an example post.",
        ]);
  
        $post2 = Post::create([
            "title" => "Example Post",
            "content" => "This is an example post 2.",
        ]);
  
        $post3 = Post::create([
            "title" => "Example Post",
            "content" => "This is an example post 3.",
        ]);
  
        dd($post->toArray(), $post2->toArray(), $post3->toArray());
    }
}

Let's Run the Application

Lets run the application using the following artisan command and lets browse the route,

php artisan serve

------------------------
http://localhost:8000/post

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides