How to use Traits - Laravel 5.2

久未见 提交于 2019-11-29 16:02:05

问题


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();
    }
}

回答1:


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!




回答2:


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'));
    }
}


来源:https://stackoverflow.com/questions/36657629/how-to-use-traits-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!