Creating routes

In the previous post about Laravel you´ve created your project in
If you tried to access the default url (something like later, you probably saw an error. Why?
The error ocurried because you need to start the server on your machine.
To do that access your project directory and start the web server:

php artisan serve

Now you can use your browser to access your application.

Inside your project there’s a folder called routes.
In the routes folder, you’ll see three files:
– api.php
– console.php
– web.php

Since we’re talking about web development our focus will be on the web.php file.
Open it within your code editor and you’ll see its content.

It says that when the user access the root of your web application the system will load the view located in

Now let’s say you want to create a contact form.

First thing to do would be to create a route to the url

Where do you think you need to implement this feature?

Correct. Add these lines into your web.php file:

Route::get('/contact', function() {
return "testing contact";

Save your file and try to reach the url
to see the result:

Good. You’ve made your first route configuration. Congratulations!

Now let’s suppose you want to pass an id as an argument.
Something like

Try to access this url and you’ll see an error.

To receive an argument, your code should look like this:

Route::get('/contact/{id}', function($id) {
return "testing contact. Id = $id";

Note that now you’re getting the argument and passing it to your function. With this strategy you can access the argument inside the function code.

But what if you try to access now?

You get an error again?

It’s because you’re no longer expecting an url without arguments.
To make an argument optional, your code should look like this:

Route::get('/contact/{id?}', function($id = null) {
return "testing contact. Id = $id";

Now we have the best case scenario:
1) If you don’t pass an argument, a null object will be passed to the function and it should work;
2) If you provide an argument, its value will be passed to the function and it will work properly too.

In the web.php file you can:
1) Call a function;
2) Call a controller;
3) Call a template (view).

If you’re planning to call a template you don’t need to specify the extension within the web.php file but it is mandatory for your template to be located in resources/view
Besides that, the file name should follow the pattern

Note that you can list your existing routes with the command below: