繁体   English   中英

在 Laravel 资源控制器中使用模型不起作用

[英]Using model in Laravel resource controller does not work

使用资源控制器时,我想检查某个 id。 我在资源控制器的每个函数中都使用了这个 id,所以我只想在构造函数中加载它一次。 但是在使用 Eloquent 模型时,我不断收到错误消息:

在 null 上调用成员函数 connection()

这是我的代码,我该如何解决?

namespace NameSpaceCompany\Utility\Controller;

use App\Http\Controllers\Controller;
use NameSpaceCompany\Utility\Model\Entity;

class StatusController extends Controller
{
    public $entity = "Status";

    public $entityModel = null;

    public function __construct()
    {
        $this->entityModel = Entity::where('entity_name',$this->entity)->first();

        dd($this->entityModel);
    }
}

我设法通过 Helper 类修复它:

$this->entity = app('EntityHelper')->getEntity(__CLASS__);

在应用服务提供商中:

$this->app->singleton('EntityHelper', function () {
    $entities = Entity::all();
    return new EntityHelper($entities);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM