30

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();
    }
}
Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
David
  • 1,987
  • 5
  • 33
  • 65

2 Answers2

39

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!

Scopey
  • 6,269
  • 1
  • 22
  • 34
  • 2
    I can achieve this with inheritance, what plus offer the traits? – Jose Rojas Apr 15 '16 at 23:15
  • 6
    PHP doesn't support multiple Inheritance and as such, will only allows you to extend a single class. With traits however, you can use as many as you want. – Thomas Maddocks Apr 16 '16 at 02:06
  • 4
    Additionally, when thinking about the structure of your object, inheritance should really be reserved for objects with similar responsibilities. Traits however can just be used to DRY two bits of classes that might not have similar responsibilities but similar methods. – Scopey Apr 16 '16 at 07:27
  • 7
    @JoseRojas Yes, the traits and inheritance may look similar. But the difference can be explained like this: Dog class will be inherited by Bulldog and Pug classes but not by Ragdoll (its a cat breed), though the trait 'eating' can be used by all the three mentioned classes. :) – Abhishek Apr 17 '16 at 08:02
3
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'));
    }
}
avn
  • 822
  • 1
  • 14
  • 31