Loading…

How to use traits in Laravel?

A Traits are a technique for code reuse in single inheritance languages.

Example

                                        

I Created a Traits directory in my Http directory named BrandTrait.php


use App\Http\Traits\BrandTrait;
class YourController extends Controller {
    use BrandTrait;
    public function addProduct() {
       //$brands = Brand::all();
       // $brands = $this->BrandTrait(); // this is wrong
       $brands = $this->brandsAll();
    }
}

Here is my BrandTrait.php

namespace App\Http\Traits;
use App\Brand;
trait BrandTrait {
    public function brandsAll() {
        // Get all the brands from the Brands model or table.
        $brands = Brand::all();
        return $brands;
    }
}

 

Suggest An Answer

No suggestions avaliable!

Latest post from Laravel Interview Questions

Ask Question