Jason Spick
Jason Spick

Reputation: 6098

Custom methods in laravel 4 controllers

I may be misunderstanding how Laravel works or maybe I missed something in the troves of documents I've poured over, and for that I apologize in advance.

Lets say I create a new controller using artisan

php artisan controller:make FooController --path /var/www/app/controllers/admin

and I set my routes:

 Route::group(array('prefix' => 'admin', 'before' => 'auth.admin'), function()
 {
    Route::any('/',           'App\Controllers\Admin\IndexController@index');
    Route::resource('foo',    'App\Controllers\Admin\FooController');
 }

Then in my controller I'll have methods for index(),create(),update(), etc. right?

What if i want a method called activate() in my FooController? It could look like this:

public function activate($id){
    return "activated";
}

Now I put a link in my index.blade.php file

 <a href="{{ URL::route('admin.foo.activate', $foo->id) }}">Activate</a>

Why does this not work? I get:

Unable to generate a URL for the named route "admin.foo.activate" as such route does not exist.

Maybe I'm not good enough with routes but this is really frustrating.

thank you in advance!

Upvotes: 1

Views: 3085

Answers (3)

Oliver Adria
Oliver Adria

Reputation: 1143

It's possibly a bit cleaner if you name the route in app/routes.php, i.e.

Route::get('admin/foo/activate/{id}', [ 'as' => 'admin.foo.activate', 'uses' => 'App\Controllers\Admin\foo@activate']);

then you can call via

<a href="{{ URL::route('admin.foo.activate', $foo->id) }}">Activate</a>

or even

{{ URL::link_to_route('admin.foo.activate', 'Activate', [$foo->id]) }}

Upvotes: 0

Jason Spick
Jason Spick

Reputation: 6098

Here is how i solved it:

I needed to user Route::get

Route::get('admin/foo/activate/{id}',    'App\Controllers\Admin\foo@activate');

then my link needed to user the namespace:

Url::action(App\Controllers\Admin\Foo@activate,$foo->id)

Upvotes: 2

Matthias S
Matthias S

Reputation: 3563

Try

URL::action('admin.foo@activate')

you are trying to route to /admin/foo/activate (for which indeed there is no route defined). Otherwise you can also define a route:

Route::controller('foo/activate/{id}',    'App\Controllers\Admin\FooController@action');

and work with your solution, but I think the first option is better.

Upvotes: 0

Related Questions