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

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptAndres Baravalle
 
Setting up your development environment
Setting up your development environmentSetting up your development environment
Setting up your development environmentNicole Ryan
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Gil Fink
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorialalexjones89
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introductionSimon Funk
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
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
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5Soheil Khodayari
 

What's hot (20)

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Maven
MavenMaven
Maven
 
Laravel Tutorial PPT
Laravel Tutorial PPTLaravel Tutorial PPT
Laravel Tutorial PPT
 
Setting up your development environment
Setting up your development environmentSetting up your development environment
Setting up your development environment
 
Java script
Java scriptJava script
Java script
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
Beginners PHP Tutorial
Beginners PHP TutorialBeginners PHP Tutorial
Beginners PHP Tutorial
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
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...
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Web Development with Laravel 5
Web Development with Laravel 5Web Development with Laravel 5
Web Development with Laravel 5
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Jquery
JqueryJquery
Jquery
 

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

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
 
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つまみぐい
 

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

The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationElement34
 
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024Primacy Infotech
 
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...Marko Lohert
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationWave PLM
 
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
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)Max Lee
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMok TH
 
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanWorkshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanNeo4j
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Henry Schreiner
 
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
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletAndrea Goulet
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfICS
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckMarc Lester
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfSrushith Repakula
 
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
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024vaibhav130304
 

Recently uploaded (20)

The Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test AutomationThe Strategic Impact of Buying vs Building in Test Automation
The Strategic Impact of Buying vs Building in Test Automation
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024
Odoo vs Shopify: Why Odoo is Best for Ecommerce Website Builder in 2024
 
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...
Reinforcement Learning – a Rewards Based Approach to Machine Learning - Marko...
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
What is an API Development- Definition, Types, Specifications, Documentation.pdf
What is an API Development- Definition, Types, Specifications, Documentation.pdfWhat is an API Development- Definition, Types, Specifications, Documentation.pdf
What is an API Development- Definition, Types, Specifications, Documentation.pdf
 
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)
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptx
 
AI Hackathon.pptx
AI                        Hackathon.pptxAI                        Hackathon.pptx
AI Hackathon.pptx
 
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanWorkshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
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)
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
Jax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined DeckJax, FL Admin Community Group 05.14.2024 Combined Deck
Jax, FL Admin Community Group 05.14.2024 Combined Deck
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Lessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdfLessons Learned from Building a Serverless Notifications System.pdf
Lessons Learned from Building a Serverless Notifications System.pdf
 
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
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 

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