SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
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!

Contenu connexe

Tendances (20)

Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
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...
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
Laravel
LaravelLaravel
Laravel
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Laravel overview
Laravel overviewLaravel overview
Laravel overview
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
AngularJS
AngularJS AngularJS
AngularJS
 
Javascript
JavascriptJavascript
Javascript
 
php
phpphp
php
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Laravel 101
Laravel 101Laravel 101
Laravel 101
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Fragment
Fragment Fragment
Fragment
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Laravel Eloquent ORM
Laravel Eloquent ORMLaravel Eloquent ORM
Laravel Eloquent ORM
 

Similaire à 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
 
Feature flagging with rails engines
Feature flagging with rails enginesFeature flagging with rails engines
Feature flagging with rails enginesEnrico Teotti
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 

Similaire à 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
 
Feature flagging with rails engines
Feature flagging with rails enginesFeature flagging with rails engines
Feature flagging with rails engines
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 

Plus de 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
 

Dernier

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
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...Shane Coughlan
 
%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 kaalfonteinmasabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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-learnAmarnathKambale
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 

Dernier (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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 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
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 

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