SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler 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!

Mais conteúdo relacionado

Mais procurados

Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Cyber Security Alliance
 

Mais procurados (20)

Waf bypassing Techniques
Waf bypassing TechniquesWaf bypassing Techniques
Waf bypassing Techniques
 
Laravel Tutorial PPT
Laravel Tutorial PPTLaravel Tutorial PPT
Laravel Tutorial PPT
 
Php functions
Php functionsPhp functions
Php functions
 
Servlet
Servlet Servlet
Servlet
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
Asfws 2014 slides why .net needs ma-cs and other serial(-ization) tales_v2.0
 
Spring Security 5
Spring Security 5Spring Security 5
Spring Security 5
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
User management
User managementUser management
User management
 
Rest API Security
Rest API SecurityRest API Security
Rest API Security
 
Java annotations
Java annotationsJava annotations
Java annotations
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
PHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginnersPHP complete reference with database concepts for beginners
PHP complete reference with database concepts for beginners
 
Fundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege EscalationFundamentals of Linux Privilege Escalation
Fundamentals of Linux Privilege Escalation
 
PHP - Introduction to PHP Forms
PHP - Introduction to PHP FormsPHP - Introduction to PHP Forms
PHP - Introduction to PHP Forms
 
Servlets
ServletsServlets
Servlets
 
Http methods
Http methodsHttp methods
Http methods
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 
cours Php
cours Phpcours Php
cours Php
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 

Semelhante a 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
 

Semelhante a 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
 

Mais de Mindfire Solutions

Mais 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
 

Último

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
+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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Último (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
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 ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+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...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
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
 
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-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

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