Monica
Monica

Reputation: 1534

Laravel 4: ErrorException Undefined variable

After trying for a few minutes. I have this on my routes.php file

Route::get('home/bookappointment/{id?}', array('as' => 'bookappointment', 'uses' => 'FrontController@getBookAppointment'));

And on my controller I have the following:

    public function getBookAppointment($id)
{
        // find all the services that are active for the especific franchise
        $activeServices = Service::whereHas('franchise', function($q) {
                $q->where('franchise_id', '=', $id);
            })->get();

        //var_dump($activeServices);die;

        return View::make('frontend/bookappointment')
                                ->with('services', $activeServices);
}

And I keep getting this error. enter image description here

What am I doing wrong?

Upvotes: 2

Views: 3193

Answers (2)

DerLola
DerLola

Reputation: 3918

The question mark after {id in your routes file indicates the id is optional. If it indeed should be optional, it should be defined as optional in your Controller.

Take the following example:

class FrontController extends BaseController {

    public function getBookAppointment($id = null)
    {
        if (!isset($id))
        {
            return Response::make('You did not pass any id');
        }
        return Response::make('You passed id ' . $id);
    }
}

Note how the method is defined with the $id argument as = null. This way you can allow for optional arguments.

Upvotes: 1

Antoine Augusti
Antoine Augusti

Reputation: 1608

You don't have access to $id in your anonymous function. Try

<?php
$activeServices = Service::whereHas('franchise', function($q) use($id) {
    $q->where('franchise_id', '=', $id);
})->get();

Take a look at the PHP documentation for additional info: http://www.php.net/manual/en/functions.anonymous.php

Upvotes: 11

Related Questions