This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

Laravel Routing Guide – How Create Route to Call a View

Updated on November 29, 2024

8 Min Read
Laravel Routing

Routing in Laravel allows users to map a URL to a specific action or controller—for example, when a URL I requested, what action is performed:

  • Data is fetched from a URL
  • Processing a form
  • Showing a user’s profile
  • Submit an order

In this article, I’ll explain Laravel routing in detail, how to set up Laravel routes, and advanced routing techniques. Assuming you know the basic introduction to installing Laravel, you can start with this guide right away.

What Is a Route in Laravel?

In Laravel, a route tells an application how it should respond to different HTTP requests. For instance, what happens when the GET request is made to specific URLs. Routes sit between the user’s request and the action your application will perform.

Routes are defined in the routes directory, which contains multiple files. routes/web.php for web application and for APIs, routes/api.php.

When a user accesses a URL, Laravel checks the routes and then matches the request to the correct URL and the HTTP method.

Developers Trust Cloudways for Hosting Their Laravel Apps

Launch your Laravel apps with ease on our developer-friendly cloud platform & experience blazing-fast speeds and performance.

Basic Route Example:

Here’s a simple example of a route in Laravel:

Route::get('/', function () {
    return view('welcome');
});

The code mentioned above defines a route for the homepage. Every time this route receives a GET request for root URL (/), It will return the view “welcome”. Views are basically the frontend of your application.

Routes and Controller Actions:

Routes can also be linked to controller methods instead of returning views directly. For example:

Route::get(‘user/{id}’, ‘UserController@show’);

This route defines a GET request for user/{id} and points to the show method of the UserController. The {id} is a dynamic route parameter that gets passed to the controller method.

Route Groups and Middleware:

Laravel routes can be grouped for better organization. You can group routes that share common attributes, like authentication or certain namespaces. Middleware can also be attached to routes to perform tasks like verifying if a user is authenticated before accessing a route.

Understanding HTTP Methods in Laravel Routing

Routes in Laravel define what your application is supposed to do (action to perform) when a specific URL is hit. Routes are linked to “controller actions”, which are categorized by the request type. For instance: GET, POST, PUT, DELETE, PATCH, and OPTIONS.

HTTP Request Methods in Laravel Routing

GET: This is used to retrieve data from the server. We use this to display data. For example:

Route::get('/home', 'HomeController@index');

POST: Is used to send data to the server for creating resources or submitting forms. We can use it this way, for example:

Route::post('/submit', 'FormController@submit');

PUT: This one is used to update an existing resource. For example:

Route::put('/user/{id}', 'UserController@update');

DELETE: This is used to delete a resource. For example, we can use it this way:

Route::delete('/user/{id}', 'UserController@destroy');

PATCH: This one is similar to the PUT method, but instead of being used to update a resource (i.e., replace the entire resource), this is used to update the user resource partially. For example:

Route::patch('/user/{id}', 'UserController@patchUpdate');

OPTIONS: This is used to retrieve information about the communication options available for a specific resource, often used in API requests. It isn’t commonly used in basic routing, but it’s relevant for handling requests that involve cross-origin resource sharing (CORS). For example:

Route::options('/user', 'UserController@options');

Example of Route with Different HTTP Methods

Here’s how you can define routes with different HTTP methods in Laravel:

  • Route::get(‘/user/{id}’, ‘UserController@show’);    // This is GET request
  • Route::post(‘/user’, ‘UserController@store’);       // This one is POST request
  • Route::put(‘/user/{id}’, ‘UserController@update’);  // This is the PUT request
  • Route::delete(‘/user/{id}’, ‘UserController@destroy’); // This is the DELETE request

Routes are defined in Laravel within the Route class. They have an HTTP verb, the route to reply to, and closure, or a controller strategy.

How to Create Routes in Laravel

Note: All the post, put, and delete requests require the CSRF token to be sent along with the request. Otherwise, the request will be rejected. Learn more about CSRF protection in Laravel official docs.

Let’s see how you can create your own routes in Laravel. I’ll create a basic route for this example, which will print a table of 2 on the view that we’ll create later.

As I progress, I’ll refine our basic route example by adding parameters, regular expressions, route naming, grouping, and middleware.

1. Define Your First Route in Laravel

Let’s start with the basics by defining a simple route in Laravel. Here’s a route that prints the multiplication table of 2 when accessed:

Route::get('/table', function () {
    for($i = 1; $i <= 10; $i++){
        echo "$i * 2 = " . $i * 2 . "<br>";
    }
});

In this example, we’re using a GET request for the /table route, which outputs the table of 2 on the screen.

2. Create Dynamic Routes with Parameters

Now, I’m adding a dynamic element by allowing users to choose the number for the multiplication table. This way, they can specify any number they want, and the route will print that number’s table:

Route::get('/table/{number}', function ($number) {
    for($i = 1; $i <= 10; $i++){
        echo "$i * $number = " . $i * $number . "<br>";
    }
});

With this route, when users access /table/3, for example, they’ll see the multiplication table for 3.

3. Make Parameters Optional for Flexibility

What if I want a default table but still allow users to specify one if they choose? Laravel allows us to set optional parameters, making our routes more flexible.

Here’s how:

Route::get('/table/{number?}', function ($number = 2) {
    for($i = 1; $i <= 10; $i++){
        echo "$i * $number = " . $i * $number . "<br>";
    }
});

In this case, if a user simply visits /table, they’ll get the table of 2 by default. But if they go to /table/5, they’ll see the table for 5.

4. Control Route Parameters with Regular Expressions

Now, to make sure that only numbers are passed to the {number} parameter, I’m adding a constraint with a regular expression. This avoids any unexpected input:

Route::get('/table/{number?}', function ($number = 2) {
    for($i = 1; $i <= 10; $i++){
        echo "$i * $number = " . $i * $number . "<br>";
    }
})->where('number', '[0-9]+');

With this constraint, if someone tries to access /table/abc, Laravel will throw an error instead of attempting to display a table.

5. Name Your Routes for Easier Reference

Naming routes is helpful when we want to reference them elsewhere in the app. Instead of hardcoding URLs, we can refer to the route by its name. Here’s how to add a name to our route:

Route::get('/table/{number?}', function ($number = 2) {
    for($i = 1; $i <= 10; $i++){
        echo "$i * $number = " . $i * $number . "<br>";
    }
})->where('number', '[0-9]+')->name('table');

To generate a URL for this route, I can now use:

$url = route('table');

And to redirect to this route:

return redirect()->route('table');

6. Group Routes for Better Organization

Now, I’m grouping routes to keep everything related to the multiplication table organized. By adding a prefix, I can bundle all table-related routes under a common URL path. Here’s an example:

Route::prefix('table')->group(function () {
    Route::get('/{number?}', function ($number = 2) {
        for ($i = 1; $i <= 10; $i++) {
            echo "$i * $number = " . $i * $number . "<br>";
        }
    });
    Route::get('/info/{number?}', 'TableController@info');
});

In this case, I’ve grouped these routes under /table, so both /table/{number} and /table/info/{number} are nested under the table prefix. This keeps my routes file clean and groups stuff related to tables.

7. Apply Middleware for Added Control

Now, I’m adding middleware to ensure that only authenticated users can access the table routes. For example:

Route::middleware(['auth'])->prefix('table')->group(function () {
    Route::get('/{number?}', function ($number = 2) {
        for ($i = 1; $i <= 10; $i++) {
            echo "$i * $number = " . $i * $number . "<br>";
        }
    });
});

In this example, the /table/{number} route can only be accessed by logged-in users.

Using a Basic Route to Call a View

In routes/web.php, define the route to return a view with the table:

Route::get('/table/{number?}', function ($number = 2) {
    // Pass the 'number' to the view
    return view('table', ['number' => $number]);
})->where('number', '[0-9]+');

This will either display the table of 2 (default) or a table for the number provided in the URL since we have an optional parameter number in the route example above.

Now you need to create a view that will be called when our URL (/table) is accessed. To create a view, go to the resources/views directory, and create a table.blade.php file. In this file, you can display the multiplication table:

Here’s the code you can add to the table.blade.php file that will display a table of the multiplication of numbers 1 through 10 for the number passed in the URL.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiplication Table</title>
</head>
<body>
    <h1>Multiplication Table for {{ $number }}</h1>
    <table border="1">
        <tr>
            <th>Multiplier</th>
            <th>Result</th>
        </tr>
        @for($i = 1; $i <= 10; $i++)
            <tr>
                <td>{{ $i }}</td>
                <td>{{ $i * $number }}</td>
            </tr>
        @endfor
    </table>
</body>
</html>

Now if you access the route URL we created on your local server, here’s what you should see:

And since we used an optional parameter in our route, I can pass a number in the URL (e.g., /table/5) to display the multiplication table for that number.

Create a Fallback Route for Undefined URLs

Now, what if the user accesses an undefined URL? Instead of showing them a generic error message, we can redirect them to another page.

We can define a fallback route using the Route::fallback method. Here’s an example:

Route::fallback(function () {
    return response()->view('404', [], 404);
});

With this, if a URL doesn’t match any existing routes we created, they’ll be directed to the errors.404 view, which we’ll create in the next step.

Enhance Laravel Routing Performance with Cloudways

Optimize your Laravel routing with Cloudways’ hosting platform, featuring advanced caching, SSD storage, and optimized server stacks for faster request handling and seamless user experiences.

Set Up a Custom 404 Page

Now let’s create a 404 page view for our fallback route. For this, create a new view file and name it 404.blade.php.

Now add this code to it:

<!DOCTYPE html>
<html>
<head>
    <title>Page Not Found</title>
    <link rel="stylesheet" href="path-to-your-css">
</head>
<body>
    <h1>Oops! Page Not Found</h1>
    <p>It looks like the page you’re looking for doesn’t exist.</p>
    <a href="{{ url('/') }}">Return to Home</a>
</body>
</html>

Now let’s test it out.

Conclusion

So there you have it. This was a basic tutorial on Laravel routes. I have covered all the related concepts in this guide, like regular expressions and route naming, binding, grouping, etc.

We also learned how to create views and how to call them with our routes. We even implemented a fallback route to direct users to a 404 page to ensure a better user experience.

You can also refer to the official Laravel routing documentation to learn more about routing. If you want to host Laravel projects, consider using Cloudways for an optimized experience.

Q) What is a Laravel route?
A) A Laravel route is a way to define how your application responds to specific HTTP requests. Routes map URLs to controller methods or closures, enabling navigation and functionality within the app.

Q) What is the difference between URL and route in Laravel?
A) A URL is the web address of a resource, while a route in Laravel is a logical mapping that defines which controller or function should handle that URL. Routes provide a flexible way to manage URLs dynamically.

Q) How to use Laravel API routes?
A) Define API routes in the routes/api.php file. These routes are stateless and intended for API endpoints. Use the Route::get, Route::post, and other methods to handle API requests.

Q) How to get route URL in Laravel?
A) Use the route() helper function to generate a URL for a named route, e.g., route(‘routeName’). Alternatively, use the url() function for custom URLs.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now