URL


Generate base URL

  • Access current URL
  • Named route URL
    • Signed URL
    URL for controller action
  • Default value
  • Introduction
  • Laravel provides several helper functions to generate URLs for applications. Mainly used for constructing URLs in templates and API responses or generating redirect responses in other parts of the application.

Basic

Generate Basic URL

Auxiliary functions
url
can be used for any URL in the application. The generated URL will automatically use the scheme ( HTTP or HTTPS ) and host from the current request:

$post = App\Post::find(1);
echo url("/posts/{$post->id}");
// http://example.com/posts/1

Access the current URL

If no path is provided to the helper function url, an Illuminate\Routing\UrlGenerator instance will be returned to allow you to access information about the current URL URL information:

// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();

The above methods can be accessed through the URL facade:

use Illuminate\Support\Facades\URL;
echo URL::current();

URL for named routes

Auxiliary functionsroute can be used to generate URLs for specified routes. The URL generated by a named route is not coupled to the URL defined on the route. Therefore, if there are any changes to the route's URL, no changes to the route function calls are required. For example, suppose your application contains the following route:

Route::get('/post/{post}', function () { 
   //
})->name('post.show');

To generate the URL for this route, you can use the helper function route like this:

echo route('post.show', ['post' => 1]);
// http://example.com/post/1

You would typically use The primary key of the Eloquent model generates the URL. Therefore, you can pass Eloquent models as parameter values. route The helper function will automatically extract the primary key of the model:

echo route('post.show', ['post' => $post]);

Helper function route Can also be used to generate URLs for routes with multiple parameters:

Route::get('/post/{post}/comment/{comment}', function () { 
   //
})->name('comment.show');
echo route('comment.show', ['post' => 1, 'comment' => 3]);
// http://example.com/post/1/comment/3

Signed URL

Laravel allows you to easily create "signed" URLs for named paths. These URLs have a "signed" hash appended to the query string, allowing Laravel to verify that the URL has not been modified since its creation. Signed URLs are particularly useful for routes that are publicly accessible but require a layer of protection against URL manipulation.

For example, you can use a signed URL to implement a public "unsubscribe" link that is emailed to your customers. To create a signed URL pointing to a path, use the facade's signedRoute method URL:

use Illuminate\Support\Facades\URL;return URL::signedRoute('unsubscribe', ['user' => 1]);

If you want to generate an expired temporary signed route URL, you can use the following temporarySignedRoute Method:

use Illuminate\Support\Facades\URL;return URL::temporarySignedRoute( 
   'unsubscribe', now()->addMinutes(30), ['user' => 1]
  );

Validate Signed Route Request

To verify that the incoming request has a valid signature, you should call hasValidSignature Incoming method Request:

use Illuminate\Http\Request;
Route::get('/unsubscribe/{user}', function (Request $request) { 
   if (! $request->hasValidSignature()) {      
      abort(401);    
    }   
   // ...
})->name('unsubscribe');

Alternatively, you can assign the Illuminate\Routing\Middleware\ValidateSignature middleware to the route. If it does not exist, this middleware should be assigned a key in the HTTP kernel's routeMiddleware array:

/**
 * 应用程序的路由中间件
 *
 * 这些中间件可能被分配给组或单独使用
 *
 * @var array
 */
 protected $routeMiddleware = [ 
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
 ];

After registering the middleware in the kernel, you can attach it to a route middle. If the incoming request does not have a valid signature, the middleware will automatically return a 403 error response:

Route::post('/unsubscribe/{user}', function (Request $request) { 
   // ...
})->name('unsubscribe')->middleware('signed');

URL for Controller Action

action function can generate a URL for a given controller action. This feature does not require you to pass the full namespace of the controller, but you do need to pass the controller class name relative to the namespace App\Http\Controllers:

$url = action('HomeController@index');

You can also use " Callable" array syntax reference action:

use App\Http\Controllers\HomeController;
$url = action([HomeController::class, 'index']);

If the controller method requires route parameters, pass them as the second parameter to the action function:

$url = action('UserController@profile', ['id' => 1]);

Default Values

For some applications, you may want to specify default values ​​for the request scope of certain URL parameters. For example, suppose some routes define {locale} parameters:

Route::get('/{locale}/posts', function () {    //})->name('post.index');

It is also very troublesome to call the auxiliary function route through locale every time. Therefore, using the URL::defaults method to define the default value of this parameter allows the parameter to always exist in the current request. This method can then be called from the routing middleware to access the current request:

<?php
  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 of the locale parameter is set, you no longer need to pass the helper function route Pass its value when generating the URL.

This article was first published on the LearnKu.com website.