How to use traits in Laravel?
A Traits are a technique for code reuse in single inheritance languages.
BY Best Interview Question ON 11 Apr 2020
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;
}
}