3

In my crud controller I am trying to get the name of the person who is currently being edited.

so

http://192.168.10.10/admin/people/93/edit

In the people crud controller

public function setup() {
dd(\App\Models\People::get()->first()->name)
}

This returns the first person not the person currently being edited.

How do I return the current person (with an id of 93 in this example)

LeBlaireau
  • 17,133
  • 33
  • 112
  • 192
  • In edit you have the id. You cannot get the name in the setup function because that executes right after the controller. Find me here if this does not make sense https://gitter.im/BackpackForLaravel/Lobby – Indra May 10 '17 at 15:43

3 Answers3

1

Ok, So since you use backpack look into CrudController to see how the method looks:

public function edit($id)
    {   
        $this->crud->hasAccessOrFail('update');

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

        $this->data['id'] = $id;

        return view('crud::edit', $this->data);
    }

So now you can overwrite the edit function and change whatever you want. You can even create a custom edit page if you so wish.

Setup on the other hand is usually used to add things like

$this->crud->addClause(...);

Or you can even get the entire constructor and put it in the setup method because setup call looks like this:

public function __construct()
    {
        // call the setup function inside this closure to also have the request there
        // this way, developers can use things stored in session (auth variables, etc)
        $this->middleware(function ($request, $next) {
            $this->setup();

            return $next($request);
        });
    }

So you could do something like \Auth::user()->id;

Also it's normal to work like this. If you only use pure laravel you will only have access to the current id in the routes that you set accordingly.

Indra
  • 692
  • 6
  • 18
0

Rahman said about find($id) method. If you want to abort 404 exception just use method findOrFail($id). In my opinion it's better way, because find($id)->name can throw

"Trying to get property of non-object error ..."

findOrFail($id) first fetch user with specified ID. If doesn't exists just throw 404, not 500.

The best answer is:

public function edit($id)
{
    return \App\Models\People::findOrFail($id);
}

Good luck.

Patryk Woziński
  • 738
  • 1
  • 6
  • 18
-1

you need person against id, try below

public function setup($id) {
dd(\App\Models\People::find($id)->name);
}
Rahman Qaiser
  • 664
  • 5
  • 18
  • 1
    setup has no parameters. since setup is declared in the parent controller you have to keep the same declaration. check the backpack manual – Indra May 17 '17 at 12:28