Creating a route using a closure in laravel

If we decide not to use an MVC pattern, we can create our routes by using a closure, or
anonymous function.

Getting ready

For this recipe, we just need a standard Laravel installation.

How to do it…

To complete this recipe, follow these steps:
1. In the app/routes.php file, add a route as follows:
Route::get(‘hello/world’, function()
{
$hello = ‘Hello ‘;
$world = ‘World!’;
return $hello . $world;
});
2. Open your browser and test the route by visiting http://your-server/hello/
world, where your-server is the URL to your app.

How its Works

Routes in Laravel are considered RESTful, which means they respond to various different
HTTP verbs. Most of the time, when simply viewing web pages, we use the GET verb, as in
Route::get. Our first parameter is the URL that we’re using for the route, and it can be
pretty much any valid URL string. In our case, when a user goes to hello/world, it will use
this route. After that is our closure, or anonymous function.
In the closure, we can pull in any data from our model, do whatever logic we want, and call
the views we want to use. In our example case, we’re just setting a couple of variables and
returning their concatenated value.

Leave a Reply

Your email address will not be published. Required fields are marked *