Laravel Passing Data to Controller

2019-08-14 19:32发布

问题:

I just starting learning laravel and was wondering how to pass data unrelated to the route to a controller. What I'm trying to accomplish is create a todo item that is able to have nested items.

View

<a class="btn btn-success" href="{{route('lists.items.create',4)}}">Create New Item</a>

The 4 is just a hard-coded example to see if it was working.

Controller

public function create(TodoList $list, $item_id = null)
{
    dd($item_id);
    return view('items.create', compact('list'));
}

So if your creating an item and don't pass in a parameter for id, it will default to null otherwise set it to whatever was passed in. However I'm getting a NotFoundHttpException. How would I be able to accomplish this.

Any help Welcome :)

回答1:

You need to define the route, for example:

Route::get('create-item/{id}', [
    'as' => 'lists.items.create', 
    'uses' => 'MyController@create'
])

Now, call the route like:

<a class="btn btn-success" href="{{route('lists.items.create', ['id' => 4])}}">Create New Item</a>