Laravel routing – Different ways of how to create routes in Laravel project

Laravel routing allows us to bind URL to a Controller’s action. It is useful when creating new pages in Laravel. You should consider the following.

  • Decide the URL for the page that user will access through the browser
  • Bind that URL to relevant Controller method.
  • Decide the view blade that will be rendered by the Controller method.

The above three things are used to define routes in Laravel. Each route binds to different and the defined Controller action.

What are REST API routes?

We can use common HTTP methods to define routes. For example get, and post methods. Below are the details of all such methods with their corresponding functions.

Http MethodCRUD OperationPurposeResponse
POSTCREATECreate a new record in the database201 – Created, 404 – Not Found, 409 – Conflict
GETREADList’s or reads records from the database200 – Ok, 404 – Not Found
PUTUPDATEUpdates or replaces record/s in database405 – Not allowed, 200 – Ok, 204 – No Content, 404 – Not Found
PATCHUPDATEUpdates or modifies record/s in the database200 – Ok, 204 – No Contents. 404 – Not Found
DELETEDELETEDelete a record from the database table200 – Ok, 404 – Page Not Found

POST – the most commonly used method, that creates a new entry from form data on a view blade. Forms are submitted using the POST method to create new records for any entity. If a record is successfully created, a 201 status code is returned.

GET – another commonly used method that reads single or multiple records or a resource. It is a read only method, and cannot modify any data.

PUT – this method is used to update data or to create data when a client supplies an id that needs to be updated.

PATCH – this method updates partial data in the database. For example, to change just the contact number of a client than the complete record.

DELETE – the method used to delete a record from database table. It returns status code 200 if deleted, or 404 is the deleted record or page is not found.

How to define a route in Laravel?

You can define or add a route in the web.php file of the routes directory.

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

Example to of all four methods to define 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?

In some cases we need routes that should not bind with a controller, and rather respond with JSON, Text, or an HTML view. Below is an example to define a route in this way.

# 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?

We can also pass optional parameters with a route, the sample code for it is shown belo.

# 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 parameters 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

Routes can be added while having certain middlewares attached to them. For example, if your application has frontend and backend components and you want only logged users to access specific URLs. In this case, you can define a middleware to check if a user is logged in and define the routes that make use of the middleware. The example below shows how you can use groups and middleware in routes.

# 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

You can also define routes with namespaces, as shown below.

# 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 of namespaces, you may group them using a namespace 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: you may not need to define whole namespace if you decide to declare routes using namespace grouping.

How to add prefix in front of each url?

You can easily prefix necessary routes and group them together in Laravel Routing. If you are creating admin routes and you want to add admin prefix in all of your routes. So, instead of going to each route and adding the prefix you can define a prefix and group all your routes under that prefix. Later it will be easy 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?

You can the get current route’s name, action or URL using the 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?

In case if there are no matching routes to a given request, you may define a 404 route. This comes up when no other route matches your incoming request.

# 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 also group routes based on specific domains and sub-domains, as shown below.

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

Hope you like this tutorial. Stay tuned to more on Laravel and other Coding Bugs!