Creating routes

In the previous post about Laravel you´ve created your project in
c:\code\Introduction_to_Lavavel\courseLaravel
If you tried to access the default url (something like http://127.0.0.1:8000/) 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:

c: 
cd\code\Introduction_to_Laravel\courseLaravel
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
/resources/views/welcome.blade.php

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

First thing to do would be to create a route to the url
http://127.0.0.1:8000/contact

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 http://127.0.0.1:8000/contact
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 http://127.0.0.1:8000/contact/1

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 http://127.0.0.1:8000/contact 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
<viewName>.blade.php

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