Unable to override automatic model find method calls since upgrading to Laravel 5.1 -
i have simple trait use include soft-deleted items few things:
trait overridetrashedtrait { public static function find($id, $columns = ['*']) { return parent::withtrashed()->find($id, $columns); } }
however, since upgrading laravel 5.1, no longer works. soft-deleted items not turn in get()
lists, , if try access page i've used route model bindings, notfoundhttpexception
.
laravel's upgrade documentation states that:
if overriding
find
method in own models , callingparent::find()
within custom method, should change callfind
method on eloquent query builder:
so changed trait accordingly:
trait overridetrashedtrait { public static function find($id, $columns = ['*']) { return static::query()->withtrashed()->find($id, $columns); } }
but appears no matter write in there, doesn't affect results. have tried put overriding find()
method directly in model, doesn't appear working either. way changes if write invalid syntax. if change $id
hardcoded id of item not soft-deleted, same result, , absolutely nothing happens if e.g. try dd('sdfg')
, doubt method called.
edit: if trigger method manually, works intended.
how can fix this?
ok here goes:
short version: model binding not use find.
longer version:
/** * register model binder wildcard. * * @param string $key * @param string $class * @param \closure|null $callback * @return void * * @throws notfoundhttpexception */ public function model($key, $class, closure $callback = null) { $this->bind($key, function ($value) use ($class, $callback) { if (is_null($value)) { return; } // model binders, attempt retrieve models using first // method on model instance. if cannot retrieve models we'll // throw not found exception otherwise return instance. $instance = new $class; if ($model = $instance->where($instance->getroutekeyname(), $value)->first()) { return $model; } // if callback supplied method call determine // should when model not found. gives these // developer little greater flexibility decide happen. if ($callback instanceof closure) { return call_user_func($callback, $value); } throw new notfoundhttpexception; }); }
line 931 of illuminate\routing\router says does:
$instance->where($instance->getroutekeyname(), $value)->first()
it uses key model used in , loads first result.
Comments
Post a Comment