Laravel URL Helper Function: action

November 21, 2016 —John Koster

action($name, $parameters = [], $absolute = true)

The action helper function can be used to generate a URL to a controller action, which is supplied as an argument to the $name parameter. If the controller action requires or accepts parameters these can be supplied by utilizing the $parameters parameter.

The following examples will use the following example controller (stored in app/Http/Controllers/ExampleController.php):

1<?php
2 
3namespace App\Http\Controllers;
4 
5class ExampleController extends Controller {
6 
7 public function sayHello($name) {
8 return "Hello, {$name}!";
9 }
10 
11}

as well as the following route definition (added to the web middleware group in app/Htpp/routes.php):

1<?php
2 
3Route::get('sayHello/{name}', 'ExampleController@sayHello');

Calling the action helper function like so:

1<?php
2 
3action('ExampleController@sayHello', ['name' => 'Jim']);

would return the following URL:

1http://laravel.artisan/sayHello/Jim

The exact URL that is generated will depend on the current domain of the site.

Notice that when the action function was called, we did not need to include the root namespace of the controller (App\Http\Controllers). Laravel will automatically add the namespace for you. Any namespaces that are not part of the root namespace must be included (such as Auth), however.

#Relative URLs

If you do want to generate the full URL to a controller action, simply supply a truth value of false for the $absolute parameter. The following example demonstrates this:

1<?php
2 
3action('ExampleController@sayHello', ['name' => 'Jim'], false)

The resulting URL of the function call would then be:

1/sayHello/Jim

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.