How to Make Traits in laravel 9

How to Make Traits in laravel 9

13-Sep-2022
| |
Image Carousel

Traits are basically a peice of code where we reuse wherever we need it , like we need to save image in different controllers so what we do , we actually use move command and save the image , whcih results in repetive same code then we use traits. Hence traits are like objects where you can't direct call them , basically they are public protected functions which are mostly call by inside a function .
Here we are consider an example of api response.

  • Create a folder Traits.
  • Creating a file app/Traits/ApiResponse.php.
  • Make custom functions.
  • Include namespace and use it in controller

Make a folder name Traits inside app like this app/Traits

and inside this Traits make a file ApiResponse.php

Paste the following code in app/Traits/ ApiResponse.php Copy

<?php
 
namespace App\Traits;
 
use Carbon\Carbon;
 
/*
|--------------------------------------------------------------------------
| Api Responser Trait
|--------------------------------------------------------------------------
|
| This trait will be used for any response we sent to clients.
|
*/
 
trait ApiResponse
{
    /**
     * Return a success JSON response.
     *
     * @param  array|string  $data
     * @param  string  $message
     * @param  int|null  $code
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($data, string $message = null, int $code = 200)
    {
        return response()->json([
            'status' => 'Success',
            'message' => $message,
            'data' => $data
        ], $code);
    }
 
    /**
     * Return an error JSON response.
     *
     * @param  string  $message
     * @param  int  $code
     * @param  array|string|null  $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error(string $message = null, int $code, $data = null)
    {
        return response()->json([
            'status' => 'Error',
            'message' => $message,
            'data' => $data
        ], $code);
    }
 
}

 

 

Now its time for calling traits in controller Copy

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Role;
use Hash;
use App\Traits\ApiResponse;
use Auth;
class DeveloperCorner extends Controller
{
  use ApiResponse;
 
public function TestTraits()
    {
      $data = 'Developer Corner';
      $message = 'Welcome to Developer Corner';
      return $this->success($data,$message);
    }
}

 

 

 I called this function by using TestTraits route through GET method

 

Now you may use and make flexible traits and feel free

Tags: how to make traits in laravel 9 , traits in laravel 9 , how to use traits in laravel 9,laravel , php ,laravel-php , mvc laravel, advance laravel , bugs in laravel , laravel advance level,
Related Articles
Load More

Newsletter