简体   繁体   中英

How can I inject different Eloquent Models into the method of a trait?

I am looking to stay DRY across controllers in my Laravel 5 application. The route I have chosen is to use a Trait with methods that I can apply to my separate controllers.

The methods in my Trait need to act upon different Model classes. They are always subclasses of the Eloquent model .

Here was my attempt:

<?php namespace Conjunto\Traits;

use Illuminate\Database\Eloquent\Model;

trait SortableTrait
{
    /**
     *
     */
    public function upPosition(Model $model)
    {
        dd($model);
    }
}

I am unfortunately getting the following error, since the Eloquent Model itself is not instantiable:

Target [Illuminate\\Database\\Eloquent\\Model] is not instantiable.

How could I still make this work with a Trait?

The solution is injecting concrete model in constructor, setting it as property and using this property in upPosition method of your Trait.

controller UserController 
{
  protected $model;

  use SortableTrait;

  public function __construct(User $user) 
  {
    $this->model = $user;
  }
}

and now in your Trait you should change your method into:

public function upPosition()
{
   dd($this->model);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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