Crud: Route Model Binding cause error

Created on 25 Dec 2017  路  4Comments  路  Source: Laravel-Backpack/CRUD

For example we use Model Binding for {user}
https://laravel.com/docs/5.5/routing#route-model-binding
then in route user/1/edit we have User model already injected by binding.
This cause an error:

Method withFakes does not exist.

The problem is here:

$this->data['entry'] = $this->crud->getEntry($id);

because in $id we have object, not numeric id. My fast fix proposition:

$this->data['entry'] = is_object($id) ? $id : $this->crud->getEntry($id);

Ask-It-On-Stack-Overflow Bug

All 4 comments

Not quite sure if this really is a bug @lloy0076 馃

Current backpack behaviour addresses $id and also the CRUD::resource route generation uses $id and no model binding.

Also as $this->crud->getEntry($id) is implemented like this:

    public function getEntry($id)
    {
        if (! $this->entry) {
            $this->entry = $this->model->findOrFail($id);
            $this->entry = $this->entry->withFakes();
        }

        return $this->entry;
    }

you could mimic the inteded behaviour by just overriding the functions and set the bound entry.

Example for edit in a CrudController subclass

function edit($id)
{
     // with model binding $id is already a model instance
    $instance = $id;

    $this->crud->entry = $instance;

    // as they will otherwise not be loaded call withFakes()
    $instance->withFakes();

    return parent::edit($instance->id);
}

another way would just be (but this would load the instance again)

function edit($id)
{
     // with model binding $id is already a model instance
    $instance = $id;

    return parent::edit($instance->id);
}

route generation uses $id and no model binding.

Binding is totally global - once set in web.php, it works everywhere also in an admin.php, separate routes (strange for me but it is how Laravel works).

I will try your proposed code soon.

Solutions confirmed (i have choose last one as the most minimalistic);) thx

As this seems to be no bug and issuer has confirmed he resolved, I鈥榣l close this one.

Was this page helpful?
0 / 5 - 0 ratings