Laravel Routes

  • Basic routing
    • Route::get($uri, $callback);
      • Route::get(‘myapp’, function(){ return “hello world”;});
        • navigating to ‘/public/myapp’ returns ‘hello world’
      • Route::get(‘welcome’, function(){ return view(‘welcome’);});
        • navigating to ‘/public/welcome’ displays welcome ‘view’.
  • Available route methods:
    • Route::get($uri, $callback);
    • Route::post($uri, $callback);
    • Route::put($uri, $callback);
    • Route::delete($uri, $callback);
    • Route::patch($uri, $callback);
    • Route::options($uri, $callback);
    • for a route that needs to respond to multiple http verbs:
      • Route::match([‘get’,’post’], ‘myapp’, function(){  return “get/post”;  });
  • CSRF protection
    • forms pointing to put, post, delete routes should include CSRF token are else the request will be rejected
    • Adding CSRF protection:
      • <form> {{csrf_filed()}} </form>
  • Route parameters
    • Route::get(‘app/{id}’, function($id){ return “parameter in the url is”. $id; });
    • may define as many parameters as required:
      • Route::get(‘app/posts/{post}/comment/{comment}’, function($postid, $commentid){ return “parameters in the url are”. $postid. $commentid; });
  • Optional parameters
    • you can have optional parameters in the route:
      • Route::get(‘user/{id?}’, function($id = null){ return null});
  • Regular expression constraints
    • may constrain the format of the router parameters with ‘where’ method for a route instance
      • Route::get(‘user/{name}’, function ($name){ return $name;’})->where(‘name’, ‘[A-Za-z]+’);
      • Route::get(‘user/{id}’, function ($id){ return $id;’})->where(‘id’, ‘[0-9]+’);
      • Route::get(‘user/{id}/{name}’, function ($id, $name){ return $id.$name;’})->where([‘name’=> ‘[A-Za-z]+’, ‘id’=>'[0-9]+]’);
  • Global constraints
  • Name Routes
  • Route grouping – very useful
    • Middleware
    • Namespaces
    • Sub-Domain routing
    • Route pre-fixes
      • Route::group(['prefix' => 'users/admin'], function () {
         Route::get('login', function () {
         return 'This is users admin login';
         Route::get('index', function () {
         return 'This is users admin home';
  • Route model binding
    • Route::get('api/users/{user}', function (App\User $user) {
          return $user->email;
  • Explicit binding
  • Form method spoofing
  • Accessing the current route

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s