You do not need to pass the full namespace of the controller. Instead, pass the controller class name relative to the App\Http\Controllers
namespace:
$url = action('HomeController@index');
use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);
If the controller method accepts route parameters, you may pass them as the second argument to the function:
$url = action('UserController@profile', ['id' => 1]);
Default Values
For some applications, you may wish to specify request-wide default values for certain URL parameters. For example, imagine many of your routes define a {locale}
parameter:
Route::get('/{locale}/posts', function () {
//
})->name('post.index');
It is cumbersome to always pass the locale
every time you call the route
helper. So, you may use the URL::defaults
method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a route middleware so that you have access to the current request:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
class SetDefaultLocaleForUrls
{
public function handle($request, Closure $next)
{
URL::defaults(['locale' => $request->user()->locale]);
return $next($request);
}
}
Once the default value for the locale
parameter has been set, you are no longer required to pass its value when generating URLs via the route
helper.
Example(1)
1.Create route with action in routes\web.php file
Route::get(
'demo/{name}',
'demoController@demo'
);
$url = action(
'demoController@demo',
['name' => 'Shiva']
);
echo '<br>'.$url;
2.Create demoController using below command
php artisan make:controller demoController
3.Open app\Http\demoController.php and implement below code in it
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class demoController extends Controller
{
public function demo($name) {
return "Hello, {$name}!";
}
}
4.To see Output use below url
http://localhost/laraveldemoproject/public/demo/shiva