SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Mindfire Solutions 1
Laravel - Routing : Basic and some
advanced concepts
-By Pallavi Dhanuka
Mindfire Solutions 2
Routing:
Introduction
Basic Routing
Routing with Parameters
Named Routing
Route filters
Route groups and prefixing
Handling Errors
Controller routing
Mindfire Solutions 3
Introduction
● Routing: the coolest feature of Laravel
● Very flexible
● All the routes can be defined in one file:
app/routes.php
Mindfire Solutions 4
Basic Route
● Can be used for static pages and no need to add any
controller ! Yes, just the view file is enough :)
Route::get('/', function(){
return 'hi';
//or return View::make('login');
});
Url: http://Localhost/
o/p: Hi (or the login page of your app)
Mindfire Solutions 5
Secured routing
Route::get('myaccount',array('https', function(){
return 'My https secured page';
}));
Url: https://localhost/myaccount
o/p: My https secured page
Url: http://localhost/myaccount
o/p: Not found exception
Mindfire Solutions 6
Route parameters
Route::get('profile/{name}', function($name)
{
return 'Hey there '. $name.' ! Welcome to whatsapp !';
});
Url: http://localhost/profile/john
o/p : Hey there john! Welcome to whatsapp!
Mindfire Solutions 7
Optional parameter
Route::get('profile/{name?}', function($name = null)
{
return 'Hey there '. $name.' ! Welcome to whatsapp !';
});
Url: http://localhost/profile/
o/p : Hey there ! Welcome to whatsapp!
Mindfire Solutions 8
Route constraints
Route::get('profile/{name?}', function($name = null)
{
return 'Hey there '. $name.' ! Welcome to whatsapp !';
})
->where('name', '[A-Za-z]+');
Url: http://localhost/profile/p45
o/p: Redirected to missing page
Mindfire Solutions 9
Global patterns
● The same constraint is applied to route parameters all
across the routes.php
Route::pattern('id', '[0-9]+');
Route::get('profile/{id}', function($id){
// Only called if {id} is numeric.
});
Mindfire Solutions 10
Route::get('messages/{type?}',function($type = 'inbox'){
return 'Showing the '.$type.' messages!';
});
Url: http://localhost/messages
o/p: Showing the inbox messages!
Route::get('user/{id}/{name}', function($id, $name){
return 'Hey there '. $name.' ! Welcome to whatsapp !';
})
->where(array('id' => '[0-9]+', 'name' => '[a-z]+'));
Url: http://localhost/user/768/jim
o/p: Hey there jim! Welcome to whatsapp !
Wake up!
Mindfire Solutions 11
Wake up!
Route::post('foo/bar', function(){
return 'Hello World';
});
Url: http://localhost/foo/bar
o/p: Error : Misssing Route
Mindfire Solutions 12
Named Routes
Route::get('long/route/user/profile', array('as' => 'profile', function(){
return 'User profile' ;
}));
Url : http://localhost/long/route/user/profile
Call : {{ route('profile') }} or Redirect::route('profile')
$name = Route::currentRouteName(); // gives current route name
Or :
Route::get('user/profile', array('as' => 'profile',
'uses' =>'UserController@showProfile'));
Mindfire Solutions 13
Route Filters
● Limit the access to a given route
● Useful in authentication and authorization
Define a filter (in app/filters.php)
Route::filter('sessionCheck', function(){
if( ! Session::has('user')){
return Redirect::to('/');
}
});
Mindfire Solutions 14
Attaching a filter
● Route::get('user', array('before' => 'sessioncheck', function(){
return 'Welcome user!';
}));
● Route::get('user', array('before' => 'sessioncheck', 'uses' =>
'UserController@showProfile'));
● Route::get('user', array('before' => array('auth', 'old'), function(){
return 'You are authenticated and over 200 years old!';
}));
Mindfire Solutions 15
# To allow the user to access only the screens fetched from the database
Route::filter('userAccess', function(){
$accessList = Session::get('user.accessList');
$screen = Request::segment(1);
$subScreen = Request::segment(2);
// the subscreens' name should be present in the access list fetched from db
// the main screen's name should be present in the access list
if( !$isAdmin && ( ($subScreen != '' && ! in_array($subScreen, $accessList))
|| ( $subScreen == '' && ! in_array($screen, $accessList)) ) ){
return Redirect::to('dashboard');
}
});
Mindfire Solutions 16
Route groups
● Wouldn’t it be great if we could encapsulate our routes, and apply a filter to the
container?
Route::group(array('before' => 'auth'), function(){
Route::get('user/accounts', function()
{
// Has Auth Filter
});
Route::get('user/profile', function(){
// Has Auth Filter
});
});
Mindfire Solutions 17
Route prefixing
● If many of your routes share a common URL structure, you could use a route prefix
Route::group(array('prefix' => 'user'), function(){
Route::get('/accounts', function()
{
return 'User account';
});
Route::get('profile', function(){
return 'User profile';
});
});
● Url : http://localhost/user/accounts
http://localhost/user/profile
Mindfire Solutions 18
Wake up! Wake up!
What will be the outcome of the below code snippet?
Route::group(array('prefix' => 'user', 'before' => 'auth'), function(){
Route::get('/accounts', function()
{
return 'User accounts'
});
Route::get('/profile', function(){
return 'User profile';
});
});
Url: http://localhost/user/profile
o/p: User profile (after getting authenticated by the 'auth' filter)
Mindfire Solutions 19
Handling errors in Laravel
● Its very easy to handle errors or missing files/routes with Laravel
● Handled in app/start/global.php
/* handles the 404 errors, missing route errors etc*/
App::missing(function($exception){
return Redirect::to('/');
});
App::error(function(Exception $exception, $code){
Log::error($exception);
});
App::fatal(function($exception){
Log::error($exception);
});
Mindfire Solutions 20
Routing with Controllers
● Controllers are registered in the composer.json
● Route declarations are not dependent on the location of
the controller class file on disk.
● The best way to handle routing for large applications is to
use RESTful Controllers
Mindfire Solutions 21
Basic Controller
class UserController extends BaseController {
public function showProfile($id){
$user = User::find($id);
return View::make('user.profile', compact('user'));
}
}
In the routes.php :
Route::get('user/{id}','UserController@showProfile');
Mindfire Solutions 22
Using Namespace
● Define the namespace before the controller class
namespace mynamesp;
● Define the route as below:
Route::get('foo','mynamespMycontroller@method');
Mindfire Solutions 23
Filters in Controllers
class UserController extends BaseController {
public function __construct(){
$this->beforeFilter('auth', array('except' => 'getLogin'));
$this->beforeFilter('csrf', array('on' => 'post'));
$this->afterFilter('log', array('only' => array('fooAction','barAction')));
}
}
Mindfire Solutions 24
RESTful Controllers
● Easily handle all the actions in a Controller
● Avoid numerous routes and business logic in routes.php
Syntax:
Route::controller('users', 'UserController');
Url: http://localhost/users/index
o/p: goes to the getIndex action of the UserController
Form posted to : {{ Url('users') }}
o/p: form posted to the postIndex action of the UserController
Mindfire Solutions 25
Find the outcome !
# Named RESTful Controllers
In my routes.php I have a named route to getIndex action:
Route::controller('blog', 'BlogController', array('getIndex' => 'home'));
And in the BlogController the method getIndex is as follows:
public function getIndex(){
return View::make('blog.home');
}
Url: http://localhost/home
O/p: Gives a not found exception.
Please note here that 'home' is the route name to be used within the application.
The uri 'blog' needs to be given in the url to access the getIndex action of the BlogController
Mindfire Solutions 26
References
● http://laravel.com/docs/routing
● http://scotch.io/tutorials/simple-and-easy-laravel-routing
Mindfire Solutions 27
Thank You!

Weitere ähnliche Inhalte

Was ist angesagt?

Hadoop REST API Security with Apache Knox Gateway
Hadoop REST API Security with Apache Knox GatewayHadoop REST API Security with Apache Knox Gateway
Hadoop REST API Security with Apache Knox Gateway
DataWorks Summit
 
Building Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPABuilding Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPA
LDAPCon
 

Was ist angesagt? (20)

Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 
MySQL InnoDB Cluster / ReplicaSet - Making Provisioning & Troubleshooting as ...
MySQL InnoDB Cluster / ReplicaSet - Making Provisioning & Troubleshooting as ...MySQL InnoDB Cluster / ReplicaSet - Making Provisioning & Troubleshooting as ...
MySQL InnoDB Cluster / ReplicaSet - Making Provisioning & Troubleshooting as ...
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
ModSecurity and NGINX: Tuning the OWASP Core Rule Set
ModSecurity and NGINX: Tuning the OWASP Core Rule SetModSecurity and NGINX: Tuning the OWASP Core Rule Set
ModSecurity and NGINX: Tuning the OWASP Core Rule Set
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
WebLogic 12c & WebLogic Mgmt Pack
WebLogic 12c & WebLogic Mgmt PackWebLogic 12c & WebLogic Mgmt Pack
WebLogic 12c & WebLogic Mgmt Pack
 
OOW16 - Oracle Enterprise Manager 13c Cloud Control for Managing Oracle E-Bus...
OOW16 - Oracle Enterprise Manager 13c Cloud Control for Managing Oracle E-Bus...OOW16 - Oracle Enterprise Manager 13c Cloud Control for Managing Oracle E-Bus...
OOW16 - Oracle Enterprise Manager 13c Cloud Control for Managing Oracle E-Bus...
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 
[Easy] How to Use Dropbox Tutorial
[Easy] How to Use Dropbox Tutorial[Easy] How to Use Dropbox Tutorial
[Easy] How to Use Dropbox Tutorial
 
Hadoop REST API Security with Apache Knox Gateway
Hadoop REST API Security with Apache Knox GatewayHadoop REST API Security with Apache Knox Gateway
Hadoop REST API Security with Apache Knox Gateway
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
NGINX: High Performance Load Balancing
NGINX: High Performance Load BalancingNGINX: High Performance Load Balancing
NGINX: High Performance Load Balancing
 
Building Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPABuilding Open Source Identity Management with FreeIPA
Building Open Source Identity Management with FreeIPA
 

Ähnlich wie Laravel Routing and Query Building

Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
Spike Brehm
 
Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8
Skilld
 
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендераAndy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
LEDC 2016
 

Ähnlich wie Laravel Routing and Query Building (20)

Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Laravel
LaravelLaravel
Laravel
 
Pluggin creation
Pluggin creationPluggin creation
Pluggin creation
 
Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate Uri
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel Controllers
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravel
 
Using and reusing CakePHP plugins
Using and reusing CakePHP pluginsUsing and reusing CakePHP plugins
Using and reusing CakePHP plugins
 
Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8
 
Renegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsRenegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails Internals
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with Laravel
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request Flow
 
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендераAndy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
Andy Postnikov - Drupal 7 vs Drupal 8: от бутстрапа до рендера
 
Lviv 2013 d7 vs d8
Lviv 2013   d7 vs d8Lviv 2013   d7 vs d8
Lviv 2013 d7 vs d8
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Feature flagging with rails engines
Feature flagging with rails enginesFeature flagging with rails engines
Feature flagging with rails engines
 

Mehr von Mindfire Solutions

Mehr von Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Kürzlich hochgeladen

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Kürzlich hochgeladen (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 

Laravel Routing and Query Building

  • 1. Mindfire Solutions 1 Laravel - Routing : Basic and some advanced concepts -By Pallavi Dhanuka
  • 2. Mindfire Solutions 2 Routing: Introduction Basic Routing Routing with Parameters Named Routing Route filters Route groups and prefixing Handling Errors Controller routing
  • 3. Mindfire Solutions 3 Introduction ● Routing: the coolest feature of Laravel ● Very flexible ● All the routes can be defined in one file: app/routes.php
  • 4. Mindfire Solutions 4 Basic Route ● Can be used for static pages and no need to add any controller ! Yes, just the view file is enough :) Route::get('/', function(){ return 'hi'; //or return View::make('login'); }); Url: http://Localhost/ o/p: Hi (or the login page of your app)
  • 5. Mindfire Solutions 5 Secured routing Route::get('myaccount',array('https', function(){ return 'My https secured page'; })); Url: https://localhost/myaccount o/p: My https secured page Url: http://localhost/myaccount o/p: Not found exception
  • 6. Mindfire Solutions 6 Route parameters Route::get('profile/{name}', function($name) { return 'Hey there '. $name.' ! Welcome to whatsapp !'; }); Url: http://localhost/profile/john o/p : Hey there john! Welcome to whatsapp!
  • 7. Mindfire Solutions 7 Optional parameter Route::get('profile/{name?}', function($name = null) { return 'Hey there '. $name.' ! Welcome to whatsapp !'; }); Url: http://localhost/profile/ o/p : Hey there ! Welcome to whatsapp!
  • 8. Mindfire Solutions 8 Route constraints Route::get('profile/{name?}', function($name = null) { return 'Hey there '. $name.' ! Welcome to whatsapp !'; }) ->where('name', '[A-Za-z]+'); Url: http://localhost/profile/p45 o/p: Redirected to missing page
  • 9. Mindfire Solutions 9 Global patterns ● The same constraint is applied to route parameters all across the routes.php Route::pattern('id', '[0-9]+'); Route::get('profile/{id}', function($id){ // Only called if {id} is numeric. });
  • 10. Mindfire Solutions 10 Route::get('messages/{type?}',function($type = 'inbox'){ return 'Showing the '.$type.' messages!'; }); Url: http://localhost/messages o/p: Showing the inbox messages! Route::get('user/{id}/{name}', function($id, $name){ return 'Hey there '. $name.' ! Welcome to whatsapp !'; }) ->where(array('id' => '[0-9]+', 'name' => '[a-z]+')); Url: http://localhost/user/768/jim o/p: Hey there jim! Welcome to whatsapp ! Wake up!
  • 11. Mindfire Solutions 11 Wake up! Route::post('foo/bar', function(){ return 'Hello World'; }); Url: http://localhost/foo/bar o/p: Error : Misssing Route
  • 12. Mindfire Solutions 12 Named Routes Route::get('long/route/user/profile', array('as' => 'profile', function(){ return 'User profile' ; })); Url : http://localhost/long/route/user/profile Call : {{ route('profile') }} or Redirect::route('profile') $name = Route::currentRouteName(); // gives current route name Or : Route::get('user/profile', array('as' => 'profile', 'uses' =>'UserController@showProfile'));
  • 13. Mindfire Solutions 13 Route Filters ● Limit the access to a given route ● Useful in authentication and authorization Define a filter (in app/filters.php) Route::filter('sessionCheck', function(){ if( ! Session::has('user')){ return Redirect::to('/'); } });
  • 14. Mindfire Solutions 14 Attaching a filter ● Route::get('user', array('before' => 'sessioncheck', function(){ return 'Welcome user!'; })); ● Route::get('user', array('before' => 'sessioncheck', 'uses' => 'UserController@showProfile')); ● Route::get('user', array('before' => array('auth', 'old'), function(){ return 'You are authenticated and over 200 years old!'; }));
  • 15. Mindfire Solutions 15 # To allow the user to access only the screens fetched from the database Route::filter('userAccess', function(){ $accessList = Session::get('user.accessList'); $screen = Request::segment(1); $subScreen = Request::segment(2); // the subscreens' name should be present in the access list fetched from db // the main screen's name should be present in the access list if( !$isAdmin && ( ($subScreen != '' && ! in_array($subScreen, $accessList)) || ( $subScreen == '' && ! in_array($screen, $accessList)) ) ){ return Redirect::to('dashboard'); } });
  • 16. Mindfire Solutions 16 Route groups ● Wouldn’t it be great if we could encapsulate our routes, and apply a filter to the container? Route::group(array('before' => 'auth'), function(){ Route::get('user/accounts', function() { // Has Auth Filter }); Route::get('user/profile', function(){ // Has Auth Filter }); });
  • 17. Mindfire Solutions 17 Route prefixing ● If many of your routes share a common URL structure, you could use a route prefix Route::group(array('prefix' => 'user'), function(){ Route::get('/accounts', function() { return 'User account'; }); Route::get('profile', function(){ return 'User profile'; }); }); ● Url : http://localhost/user/accounts http://localhost/user/profile
  • 18. Mindfire Solutions 18 Wake up! Wake up! What will be the outcome of the below code snippet? Route::group(array('prefix' => 'user', 'before' => 'auth'), function(){ Route::get('/accounts', function() { return 'User accounts' }); Route::get('/profile', function(){ return 'User profile'; }); }); Url: http://localhost/user/profile o/p: User profile (after getting authenticated by the 'auth' filter)
  • 19. Mindfire Solutions 19 Handling errors in Laravel ● Its very easy to handle errors or missing files/routes with Laravel ● Handled in app/start/global.php /* handles the 404 errors, missing route errors etc*/ App::missing(function($exception){ return Redirect::to('/'); }); App::error(function(Exception $exception, $code){ Log::error($exception); }); App::fatal(function($exception){ Log::error($exception); });
  • 20. Mindfire Solutions 20 Routing with Controllers ● Controllers are registered in the composer.json ● Route declarations are not dependent on the location of the controller class file on disk. ● The best way to handle routing for large applications is to use RESTful Controllers
  • 21. Mindfire Solutions 21 Basic Controller class UserController extends BaseController { public function showProfile($id){ $user = User::find($id); return View::make('user.profile', compact('user')); } } In the routes.php : Route::get('user/{id}','UserController@showProfile');
  • 22. Mindfire Solutions 22 Using Namespace ● Define the namespace before the controller class namespace mynamesp; ● Define the route as below: Route::get('foo','mynamespMycontroller@method');
  • 23. Mindfire Solutions 23 Filters in Controllers class UserController extends BaseController { public function __construct(){ $this->beforeFilter('auth', array('except' => 'getLogin')); $this->beforeFilter('csrf', array('on' => 'post')); $this->afterFilter('log', array('only' => array('fooAction','barAction'))); } }
  • 24. Mindfire Solutions 24 RESTful Controllers ● Easily handle all the actions in a Controller ● Avoid numerous routes and business logic in routes.php Syntax: Route::controller('users', 'UserController'); Url: http://localhost/users/index o/p: goes to the getIndex action of the UserController Form posted to : {{ Url('users') }} o/p: form posted to the postIndex action of the UserController
  • 25. Mindfire Solutions 25 Find the outcome ! # Named RESTful Controllers In my routes.php I have a named route to getIndex action: Route::controller('blog', 'BlogController', array('getIndex' => 'home')); And in the BlogController the method getIndex is as follows: public function getIndex(){ return View::make('blog.home'); } Url: http://localhost/home O/p: Gives a not found exception. Please note here that 'home' is the route name to be used within the application. The uri 'blog' needs to be given in the url to access the getIndex action of the BlogController
  • 26. Mindfire Solutions 26 References ● http://laravel.com/docs/routing ● http://scotch.io/tutorials/simple-and-easy-laravel-routing