SlideShare a Scribd company logo
1 of 27
Download to read offline
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!

More Related Content

What's hot

Lecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxLecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxSaziaRahman
 
Hypertext transfer protocol (http)
Hypertext transfer protocol (http)Hypertext transfer protocol (http)
Hypertext transfer protocol (http)Shimona Agarwal
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and responseSahil Agarwal
 
Html text and formatting
Html text and formattingHtml text and formatting
Html text and formattingeShikshak
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 

What's hot (20)

Lecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptxLecture 2_ Intro to laravel.pptx
Lecture 2_ Intro to laravel.pptx
 
Hypertext transfer protocol (http)
Hypertext transfer protocol (http)Hypertext transfer protocol (http)
Hypertext transfer protocol (http)
 
css.ppt
css.pptcss.ppt
css.ppt
 
Servlets
ServletsServlets
Servlets
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
HTTP request and response
HTTP request and responseHTTP request and response
HTTP request and response
 
Html text and formatting
Html text and formattingHtml text and formatting
Html text and formatting
 
Web Application
Web ApplicationWeb Application
Web Application
 
Servlets
ServletsServlets
Servlets
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Javascript
JavascriptJavascript
Javascript
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Java swing
Java swingJava swing
Java swing
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Html Ppt
Html PptHtml Ppt
Html Ppt
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 

Similar to Laravel Routing and Query Building

Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentialsPramod Kadam
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriAbdul Malik Ikhsan
 
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 serverSpike Brehm
 
Binary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio Academy 2016: Laravel Controllers
Binary Studio Academy 2016: Laravel ControllersBinary Studio
 
Web services with laravel
Web services with laravelWeb services with laravel
Web services with laravelConfiz
 
Using and reusing CakePHP plugins
Using and reusing CakePHP pluginsUsing and reusing CakePHP plugins
Using and reusing CakePHP pluginsPierre MARTIN
 
Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8Lviv 2013 d7 vs d8
Lviv 2013 d7 vs d8Skilld
 
Renegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsRenegades Guide to Hacking Rails Internals
Renegades Guide to Hacking Rails InternalsAllan Grant
 
Web service with Laravel
Web service with LaravelWeb service with Laravel
Web service with LaravelAbuzer Firdousi
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)xSawyer
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowVrann Tulika
 
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
 
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...Dilouar Hossain
 
Feature flagging with rails engines
Feature flagging with rails enginesFeature flagging with rails engines
Feature flagging with rails enginesEnrico Teotti
 

Similar to 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
 

More from 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
 

Recently uploaded

Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Eraconfluent
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMarkus Moeller
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AIAGATSoftware
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConNatan Silnitsky
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)Roberto Bettazzoni
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In sowetokasambamuno
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfkalichargn70th171
 
From Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST APIFrom Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST APIInflectra
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?NYGGS Automation Suite
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In hararekasambamuno
 
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Abortion Clinic
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acreskasambamuno
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdfSelfMade bd
 
Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14VMware Tanzu
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Henry Schreiner
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...CloudMetic
 

Recently uploaded (20)

Evolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI EraEvolving Data Governance for the Real-time Streaming and AI Era
Evolving Data Governance for the Real-time Streaming and AI Era
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
BusinessGPT - Security and Governance for Generative AI
BusinessGPT  - Security and Governance for Generative AIBusinessGPT  - Security and Governance for Generative AI
BusinessGPT - Security and Governance for Generative AI
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
^Clinic ^%[+27788225528*Abortion Pills For Sale In soweto
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
From Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST APIFrom Theory to Practice: Utilizing SpiraPlan's REST API
From Theory to Practice: Utilizing SpiraPlan's REST API
 
What is a Recruitment Management Software?
What is a Recruitment Management Software?What is a Recruitment Management Software?
What is a Recruitment Management Software?
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
^Clinic ^%[+27788225528*Abortion Pills For Sale In harare
 
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
Sinoville Clinic ](+27832195400*)[🏥Abortion Pill Prices Sinoville ● Women's A...
 
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
^Clinic ^%[+27788225528*Abortion Pills For Sale In birch acres
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
 
Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14Spring into AI presented by Dan Vega 5/14
Spring into AI presented by Dan Vega 5/14
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
Abortion Clinic In Springs ](+27832195400*)[ 🏥 Safe Abortion Pills in Springs...
 
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...
Salesforce Introduced Zero Copy Partner Network to Simplify the Process of In...
 

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