Basics routing and controllers in laravel 5

As discussed in last tutorial, requests are mapped by the routes (in the file app >> Http >> routes.php). By default route.php contains the following code:

  1. <?php
  2. /*
  3. |--------------------------------------------------------------------------
  4. | Application Routes
  5. |--------------------------------------------------------------------------
  6. |
  7. | Here is where you can register all of the routes for an application.
  8. | It's a breeze. Simply tell Laravel the URIs it should respond to
  9. | and give it the controller to call when that URI is requested.
  10. |
  11. */
  12. Route::get('/', 'WelcomeController@index');
  13. Route::get('home', 'HomeController@index');
  14. Route::controllers([
  15. 'auth' => 'Auth\AuthController',
  16. 'password' => 'Auth\PasswordController',
  17. ]);

Route class has get function which handles GET type requests. It takes two parameters: an url and a closure. In line 14, the url is '/' (means domain name, i.e. www.your-domain.com in production or localhost:8000 on local server). WelcomeController@index is pointing to index() function inside app >> Http >> Controllers >> WelcomeController. It means index() function will execute when we send request for '/'. Similarly when we request for 'localhost:8000/home' then index() function of class HomeController will be executed.

First response:

Now add this code in the end of the file:

  1. Route::get('request',function(){
  2. return 'this is my first response';
  3. });

Now start server and open link localhost:8000/request. The function (second argument) will execute and will return string which will be displayed on the webpage.

Other routing verbs:

Just like get(), Route class also has functions for other request types:

  • post('url', 'closure') : It is used for post type requests (like for submitting forms).
  • put('url', 'closure') : It is used for inserting data in database tables.
  • delete('url', 'closure'): It is used for deleting something from database.
  • match('['get', 'post']','url', 'closure'): This function accepts more than one type of requests. In this case, first argument is array of request types which are to be handled.
  • any('url', 'closure'): This function accepts all types of requests.

NOTE:

  1. post(), put() and delete() function will check csrf_token. For using these types, your must add _token in your form.
    1. <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
  2. HTML forms do not support put and delete methods. So you will have to add one more hidden field named _method.
    1. <form action="/action" method="POST">
    2. <input type="hidden" name="_method" value="PUT">
    3. <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
    4. </form>

Controller:

In real world, we have to do some operations and after it we have to render HTML content (or may be some other content) which is usually large in size. So, operations are separately written in the controllers (just like in WelcomeController and HomeController) and content is stored at different place. Now modify our above code like this:

  1. Route::get('request','WelcomeController@my_request');

Now open app >> Http >> HomeController.php and add this function in the class HomeController.

  1. public function my_request()
  2. {
  3. $string = 'this is response from controller';
  4. return $string;
  5. }

Comment this line in constructor: $this->middleware('guest'); because this line is using database table. We will use it after reading about databases in laravel.

Now open url localhost:8000/request again. You will get $string.

Create a Controller:

The controller is generated by using command:

  1. php artisan make:controller YourController

This command will generate a file with name YourController.php. There is a class inside this file with name YourController which contains common functions: index, create, store, show, edit, delete, update and distroy.

Route parameters:

Sometimes we need dynamic urls. For example, we want to pass user id in url. We can capture these ids from url and can pass it to function as an argument.

  1. // change routes.php to like this
  2. Route::get('request/{id}','YourController@index');
  3. // change your function in class YourController
  4. // add parameter to function
  5. public function index($id)
  6. {
  7. $string = "this is response from controller and your id is $id";
  8. return $string;
  9. }

Now try these urls:

localhost:8000/request/45412

localhost:8000/request/43422

localhost:8000/request/28411

NOTE:

  • Url is captured by writing {parameter_name}. The name inside the braces {} and the parameter name must be same.
  • For default parameters use a question mark after parameter_name
    1. // in routes.php
    2. // change routes.php to like this
    3. Route::get('request/{id?}','YourController@index');
    4. //in YourController.php
    5. // add default parameter to function
    6. public function index($id = 111111)
    7. {
    8. $string = "this is response from controller and your id is $id";
    9. return $string;
    10. }

Rendering views:

views are the templates which are rendered to the requests. These are placed in folder resources >> views. For example index() function in WelcomeController.php is rendering welcome.blade.php file using view() function.

Note that:

  • only name of the file is passed to the view() function without any extension.
  • view() function will work only with .blade.php and .php files. .blade.php files are laravel template files and you can also write simple html/ php inside these files. In other words, you can assume these files as .php files. In additional, these files supports template features (discussed in next tutorial).
  1. public function index()
  2. {
  3. return view('welcome');
  4. }

More Tutorials on laravel in this series:



About Harish Kumar

Harish is an interested person in the field of web development and blogging. He works for the need of young web developers in learning various languages, latest technologies and other essential tips and tricks. If you need some help or you have some suggestion then you email him at harish@findalltogether.com without any hesitation. You can also suggest/demand for articles of your own choice.

Related Articles

Laravel is a MVC framework. Models are the real world entities in data form. Views are the response content to the vi...
Laravel framework architecture
Routes map urls with the controllers. In this section we will read about how route maps urls with controllers and how...
Basics routing and controllers in laravel 5
Views are the HTML content served by the server. These are served by returning from controllers. Views are .php or .b...
View in Laravel 5

Login or Sign up to leave comment.