Lovelock
Lovelock

Reputation: 8075

Custom method instead of resource for Laravel routes

Using 4.2 and trying to add a custom method to my controller.

My routes are:

Route::get('ticket/close_ticket/{id}', 'TicketController@close_ticket');
Route::resource('ticket', 'TicketController');

Everything CRUD wise works as it should, but at the bottom of my TicketController I have this basic function:

public function close_ticket($id) {
    return "saved - closed";
}

When I am showing a link to route on my page:

{{ link_to_route('ticket/close_ticket/'.$ticket->id, 'Mark As Closed', array($ticket->id), array('class' => 'btn btn-success')) }}

I constantly get a route not defined error, but it surely is defined...?

Any ideas where this is going wrong?

Upvotes: 2

Views: 731

Answers (2)

JoeCoder
JoeCoder

Reputation: 880

The laravel helper method link_to_route generates an HTML link. Which mean when clicked, the user will be performing a GET request.

In your routes file, you are defining this as a POST route.

Route::post(...)

Also, take a look at the docs for link_to_route here:

http://laravel.com/docs/4.2/helpers

You'll see that the first argument should be just the route name, without the ID appended.

Upvotes: 0

patricus
patricus

Reputation: 62228

link_to_route expects a route name, not a url. This is why you are getting 'route not defined' errors, because you have not defined a route with the name you supplied to link_to_route. If you give your route a name, you can use link_to_route.

Given the following route definition, the name of the route is now 'close_ticket':

Route::get('ticket/close_ticket/{id}', array('as' => 'close_ticket', 'uses' => 'TicketController@close_ticket'));

The value for the 'as' key is the route name. This is the value to use in link_to_route:

{{ link_to_route('close_ticket', 'Mark As Closed', array($ticket->id), array('class' => 'btn btn-success')) }}

Upvotes: 1

Related Questions