Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Traits - Laravel 5.2

I'm new to Traits, but I have a lot of code that is repeating in my functions, and I want to use Traits to make the code less messy. I have made a Traits directory in my Http directory with a Trait called BrandsTrait.php. And all it does is call on all Brands. But when I try to call BrandsTrait in my Products Controller, like this:

use App\Http\Traits\BrandsTrait;  class ProductsController extends Controller {      use BrandsTrait;      public function addProduct() {          //$brands = Brand::all();          $brands = $this->BrandsTrait();          return view('admin.product.add', compact('brands'));     } } 

it gives me an error saying Method [BrandsTrait] does not exist. Am I suppose to initialize something, or call it differently?

Here is my BrandsTrait.php

<?php namespace App\Http\Traits;  use App\Brand;  trait BrandsTrait {     public function brandsAll() {         // Get all the brands from the Brands Table.         Brand::all();     } } 
like image 462
David Avatar asked Apr 15 '16 22:04

David


People also ask

How traits are used in PHP?

Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected).

Where are traits located in laravel?

In terms of placement you should treat traits like classes. That means put them inside the app directory.


2 Answers

Think of traits like defining a section of your class in a different place which can be shared by many classes. By placing use BrandsTrait in your class it has that section.

What you want to write is

$brands = $this->brandsAll(); 

That is the name of the method in your trait.

Also - don't forget to add a return to your brandsAll method!

like image 55
Scopey Avatar answered Sep 21 '22 00:09

Scopey


use App\Http\Traits\BrandsTrait;  class ProductsController extends Controller {      use BrandsTrait;      public function addProduct() {          //$brands = Brand::all();          $brands = $this->brandsAll();          return view('admin.product.add', compact('brands'));     } } 
like image 32
Sonford Son Onyango Avatar answered Sep 19 '22 00:09

Sonford Son Onyango