1

I started to learn Laravel a couple of days ago. Right now I have a problem with a variable in my controller, I always get this error: "Undefined variable: server_id".

My route file looks like this:

Route::get('servers/{server_id}','ServersController@show');

And the action method in the related controller:

public function show($server_id)
{
    $details = Server::with(array('details' => function($query)
    {
        $query->where('server_id', '=', $server_id);

    }))->get();

    return View::make('servers.show')->with('details', $details);
}

I can use the var. $server_id in the function and also pass it to the view. But i can't use it in the where clause for the database query.

I hope someone could explain me what the problem is and how to solve this.

2 Answers 2

1

The Model::with() method means that when you instantiate an object of a model, you also load some other collection at the same time. This is useful for avoiding unnecessary database calls.

I can't be certain from your code, but it looks like you want to find the server with an id of $server_id, not load some other things as well. If this is correct, you can clean your code up considerably, like this:

public function show($server_id)
{
    $details = Server::find($server_id);
    return View::make('servers.show')->with('details', $details);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You're using a closure and it has a different scope, you should pass $server_id variable to it using use keyword.

PHP document says:

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Read more about Anonymous functions

public function show($server_id)
{
    $details = Server::with(array('details' => function($query) use ($server_id)
        {
            $query->where('server_id', '=', $server_id);
        }))->get();

    return View::make('servers.show')->with('details', $details);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.