Routing in Laravel

Basic Routing

Routing is the process by which we decide which method to call on the basis of request.

We will write the routes in routes.php in app directory.

If you will open your routes.php file you will see this code:

 

Here return View::make(‘hello’); will execute when user will open root url of domain.

In return View::make(‘hello’);, View:: represents that we are going to load an html template file in views directory. hello is the file name in views directory.

So if user will open domain like http://localhost:8000 then it will open hello.php file located in views directory.

In laravel you don’t echo anything, you have to return.

Now change your routes code to this

Now open the http://localhost:8000/ again.

return text from routes
return text from routes

So whatever we return will show in browser.

Now lets say we want to open home.php if user open http://localhost:8000/home for that we will add this code in our route.

Here Route::get(‘/home’, function() shows if user add /home in url then this closure will execute.

 

If you want to open home.php if user open http://localhost:8000/user then simply change code to this

 

Route::get means user is making get request.

If you want user to make post request then we have to do this

 

 

I hope you have understood how route is going to work.

Now lets how can we pass parameters in our url.

Route Parameters

Suppose you want to pass some parameter in your url like http://localhost:8000/user/1

Then your routes will be

 

You can use variable like this in view file

 

 

You can add some validation too.

 

To pass more than one parameter change route to like this

Later we will see how to use routes when using Laravel controllers.

 

Share this article: