Laravel routing

Laravel routes are used to bind url to controller action. When you create new pages in laravel you have to remember three things.

  • You first decide what would be the url that user will access via browser
  • How you can bind this url with a specific controller methods
  • Which view will be rendered by the controller method

When you are learning laravel framework the first thing you will do after installation is to define routes. Each route will bind url with a specific controller action. In this tutorial we will only learn about routing.

What is REST api routes?

Folllowings are some of the commonly used http methods: These methods basically corresponds to create, read, update and delete operations.

Http Method CRUD Purpose Response
POST CREATE Used to create a record in the database 201 - created, 404 - Not Found, 409 - Conflict
GET READ Used to list records from the database 200 - Ok, 404 - Not Found
PUT UPDATE Used to update or replace record in database 405 - Not allowed, 200 - Ok, 204 - No Content, 404 - Not Found
PATCH UPDATE Used to update or modify the records in the database 200 - Ok, 204 - No Contents. 404 - Not Found
DELETE DELETE Used to delete a record from the table 200 - Ok, 404 - Page Not Found

POST - commonly used method to create new record or resource. Form is submitted via POST method and data submitted via this method can not be seen via browser url. When record is created successfully it returns with 201 status code.

GET - commonly used method to read single or multiple records or resource. It is basically read only method. It does not modify any data.

PUT - commonly used method to update data or to create data in case client supply the id that needs to be updated.

PATCH - commonly used method to update partial data in the database rather then supplying all data for a single record.

DELETE - commonly used method to delete a record or resource

How to define route in laravel?

Routes in laravel are defined in following location:

  • routes/api.php       -> Routes for url prefixed with /api
  • routes/web.php     -> All web routes are defined here

Followings are some of the example of basic routes:

# Defines a route that lists all the users using GET method
Route::get('users', 'UserController@show')->name('users');

# Defines a route that creates user using POST method
Route::post('/users', 'UserController@create');

# Defines a route that update user partially using PATCH method
Route::patch('/users/:id', 'UserController@update');

# Defines a route that deletes user using DELETE method
Route::delete('/users/:id', 'UserController@delete');

How to define a route without controller?

It is very easy to create a route that does not binds with any controller and response with either text, json or html view. Consider following example:

# Creates a login route with .html extension and returns view
Route::get('members/login.html', function() { 
   return View::make('members.login'); 
});

# Route that returns view directly using GET method
Route::view('/dashboard', 'dashboard');

# Route that returns view by passing some variables to view
Route::view('/welcome', 'welcome', ['name' => 'Sandip Patel']);

How to define routes with parameters?

To define routes with or without optional parameter in laravel followings are some of the examples:

# Defines a routes where id is dynamic 
# Controller must define this $id param as an argument
Route::get('/users/:id', 'UserController@get');

# Defines a routes where id is optional parameter
Route::get('/users/{id?}', 'UserController@get');

# Defines a routes where id is required parameter
Route::get('/users/{id}', 'UserController@get');

How to validate route parameters?

You can also validate route params using regular expression to restrict parameter with certain types.

# Define a route where id should be numeric only
Route::get('/users/{id}', 'UserController@get')->where('id', '[0-9]+');

# Define a route where name should be alpha only
Route::get('/users/{name}', 'UserController@get')->where('name', '[A-Za-z]+');

# Define a route where name should be alpha only and id should be numeric only
Route::get('/users/{id}/{name}', 'UserController@get')->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

Routes with groups and middlewares

If you decided to group some routes that needs to have certain middlewares attached to them you can easily define them in laravel. Let say that your application has both front and backend.

Only logged in users are allowed to access some urls. You can define a middleware that checks to see if user is logged on or not and then group some routes so that they implement such middleware.

Let's check the following examples:

# Group routes that has middleware that checks to see if user
# Is logged on only logged in users are allowed to access this routes
Route::middleware(['isLoggedIn'])->group(function () {
    Route::get('users', 'UserController@show')->name('users');
    Route::get('users/:id', 'UserController@get')->name('user_get');
});

# Group routes that are public only can be accessed without user is logged on
Route::middleware(['web'])->group(function () {
    Route::get('login', 'UserController@login')->name('login');
    Route::get('logout', 'UserController@logout')->name('logout');
});

Define routes with namespaces

If you are working with namespaces and you do not want to bother writing full namespace in every url just like below example:

# Defines all the routes that resides in App/Http/Controllers/User folder
Route::get('users', 'App\Http\Controllers\User\UserController@show')->name('users');
Route::get('users/:id', 'App\Http\Controllers\User\UserController@get')->name('user_get');

If you have more routes that repeats the same patterns you can easily group them using namespace and use them as shown below:

# Defines all the routes that resides in App/Http/Controllers/User folder
Route::namespace('User')->group(function () {
    Route::get('users', 'UserController@show')->name('users');
    Route::get('users/:id', 'UserController@get')->name('user_get');
});

Note, we do not need to define whole namespace if we decide to declare routes using namespace grouping.

How to add prefix in front of each url?

Using laravel routing you can easily prefix necessary routes and group them together. Consider you are creating admin routes and you want to add admin prefix in all of your routes rather then going to each route and adding the prefix you want to define prefix and group all your routes under that prefix. Later it will be easily to change the prefix in case you decide to prefix /admin with /something.

# Prefix routes with admin and group them together
Route::prefix('admin')->group(function() {
    Route::get('users', 'UserController@show')->name('users');                  i.e. admin/users
    Route::get('users/:id', 'UserController@get')->name('user_get');            i.e. admin/users/:id
});

How to get current route name or action or route?

To get current route name or action or url you can use following methods:

# Get current route
$route = Route::current();

# get current route name
$name = Route::currentRouteName();

# get current route controller action
$action = Route::currentRouteAction();

How to define 404 route?

Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Say you want to define 404 page when no other routes are matched you can use following route:

# Define not found route
Route::fallback('HomeController@notFound')->name('notFound');  

# Define 404 route without controller
Route::fallback(function () {
    return view("404");
});

How to group routes based on sub-domain?

You can group certain routes specific to certain sub domains. You can define them as following:

Route::domain('{sub_domain}.example.com')->group(function () {
    Route::get('user/{id}', function ($sub_domain, $id) {
        // your controller logic goes here
    });
});

I hope you like this tutorial. If you have any questions please comment or share your love by clicking the heart below. Thank you.