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?

这是我的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();
    }
}

推荐答案

想一想你的特点,比如在一个不同的地方定义一个可以被许多班级共享的班级.通过在你的班级中排名use BrandsTrait,它就有了这个部分.

What you want to write is

$brands = $this->brandsAll();

That is the name of the method in your trait.

另外,别忘了给你的brandsAll方法加上一个回报!

Laravel相关问答推荐

发送邮箱后,Laravel重定向偶尔会导致错误500

为什么我的 Laravel 开发服务器不提供 public 文件夹下的文件?

Dompdf 古吉拉特语和印地语文本未正确显示

未找到 apiResource 404 中的变量

在 laravel 中查询此类数据的最佳做法是什么?

如何在 laravel 5.8 中显示自定义消息?

处理程序类中的错误 - Laravel

Laravel 5.3 创建模型返回字段没有默认值

如何在 Laravel 5.5 中扩展 vendor 包服务提供者

会话中的 Laravel 存储数组

从 sqlite DB 登录 Laravel,得到PDOException 找不到驱动程序

调用未定义的函数 mb_strimwidth

Array_unique 上一个 laravel Eloquent的集合

使用 laravel eloquent 关系检索除 NULL 之外的所有记录

Laravel 无法创建根目录

如何在 Laravel 视图中找到当前语言?

Select,where JSON 包含数组

我在哪里放置可以显示 Flash 消息的 Laravel 4 辅助函数?

assets资源不引用公用文件夹(Laravel)

laravel如何访问具有表编号名称的列?