Friday, 22 April 2016

Unknown

Controllers in laravel-Why to use controller,What is Controller ,how to use it.

"Controllers to make laravel programming easy"
Why to use a Controller :
 
Programming is art.

In routes.php file we can write request handling logic but that is not a good programming,we are professional programmer .and wrting all code in single file is not professional.
Here comes a controller in picture.
"Controller allows us to write a related request handling logic into Controller classes."
What is Controller :

"Controller is a class for writing request logic for requests."


How to Create Controller 

Using artisan Console:
Step 1 : Run Composer in your root directory.
Step 2 : Type following command -
"php artisan make:controller NameOfController"

How Controller looks like: 


Controller in laravel-easylaravel.blogspot.com


Methods in Controller :
Methods in Controller is called when specific route request is made.

In above HomeController image ,index() is method which can be called for specific request.

How to Call Controller in Route.php :
Code to call HomeController for /home route in routes.php file -
"Route::get('/home', 'HomeController@index');"
index() method is called when get request is made for /home in browser.



Apply Middleware for Specific Controller :

Code to apply 'auth' middleware  for /home route in routes.php file -
"Route::get('/home',['middleware'=>'auth','uses' =>  'HomeController@index');"

So in above code auth middleware is applied to every method in HomeController.

 Notes:
  • Every Controller extends Controller Class in laravel.

Unknown

About Unknown -

Freelancer,Entrepreneur,Aesthetic bodybuilder.

    Knows :
  • Laravel Framework
  • Ionic Framework + Angular JS
  • Bootstrap
  • CSS
  • Jquery

Subscribe to this Blog via Email :