Josh
Josh

Reputation: 6139

Laravel 4: undefined variable error when submitting data from the view

I'm trying building a timer app - this form should submit the time (which it does) AND the client name as populated from the database, it looks like this:

{{ Form::open(array('action' => 'TasksController@store', 'name' => 'timer')) }}
    {{ Form::select('client', $client , Input::old('client')) }}
    {{ Form::hidden('duration', '', array('id' => 'val', 'name' => 'duration')) }}
    {{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}

My controller that generates this page looks like this:

public function index()
{
    $client = DB::table('clients')->orderBy('name', 'asc')->lists('name','id');
    return View::make('tasks.index', compact('task', 'client'));
}

I am getting a "Undefined variable: client" when I submit the form. I can't see why.

What am I doing wrong?

EDIT: the store function in my TasksController looks like this:

public function store()
{
    $input = Input::all();  
    $v = Validator::make($input, Task::$rules);
    if($v->passes())
    {
        $this->task->create($input);
        return View::make('tasks.index');
    }
    return View::make('tasks.index')
        ->withInput()
        ->withErrors($v)
        ->with('message', 'There were validation errors.');
}

Upvotes: 0

Views: 2130

Answers (1)

Laurence
Laurence

Reputation: 60058

You are returning the View::make() from your store() function, which is not the 'resourceful' way of doing it.

Your view is expecting to have $client included in it - but because store() does not return a $client - the error is generated.

Assuming you are using a resourceful controller - your store function should look like this:

public function store()
{
    $input = Input::all();  
    $v = Validator::make($input, Task::$rules);
    if($v->passes())
    {
        $this->task->create($input);
        return Redirect::route('tasks.index');  // Let the index() function handle the view generation
    }
    return Redirect::back()  // Return back to where you came from and let that method handle the view generation
        ->withInput()
        ->withErrors($v)
        ->with('message', 'There were validation errors.');
}

Upvotes: 2

Related Questions