SlideShare a Scribd company logo
1 of 44
Download to read offline
RESTful API development in Laravel 4
Christopher Pecoraro
phpDay 2014
Verona, Italy
May 16th-17th, 2014
I was born in 1976 in Pittsburgh, Pennsylvania, USA.
I have been living in Mondello, Sicily since 2009.
Two households both alike in dignity…
Triangular...
Triangular...
...with a fountain...
...with a fountain...
...and a temple.
...and a temple.
the first integrated viral media company
Laravel
A PHP 5.3 PHP 5.4 framework
Laravel Version Minimum PHP version required
4.0 5.3
4.1 5.3
4.2 5.4
Upgrade to at least PHP 5.4, if not PHP 5.5: Trust Rasmus and Lorna
Jane
In fair Verona, where we lay our scene…
Worldwide growth in Google search from January 2012 - Present
Laravel takes advantage of the Facade pattern:
Input::get('foo');
Installing Laravel
● Download: http://laravel.com/laravel.phar
● sudo apt-get install php5-mcrypt
● Rename laravel.phar to laravel and move it to /usr/local/bin
● laravel new blog ("blog" is the project name in this case.)
● chmod -R 777 app/storage
Installing Laravel
Other options:
● Download a Laravel Vagrant box.
● Use forge.laravel.com:
○ Deploy a box with PHP 5.5, Hack (Beta), and HHVM
○ Tuned specifically for Laravel on Digital Ocean, RackSpace, etc.
Laravel has an expressive syntax, easing common tasks such as:
● authentication
● routing
● sessions
● caching
Laravel combines aspects of other frameworks such as:
● Ruby on Rails (active record)
● ASP.NET MVC
Laravel features:
● inversion of control (IoC) container
● database migration
● unit testing support (PHPUnit)
Laravel application structure
Important files and directories:
/app
/models
/controllers
/views
routes.php
filters.php
/public (assets such as javascript, css files)
/config (settings for database drivers, smtp, etc.)
Relevant Terms:
● Eloquent ORM
● Artisan CLI
● Resource Controller
Eloquent ORM
Acts as the M (model) part of MVC
● It allows developers to use an object-oriented approach.
● Interacts with database tables by representing them as models.
Case study: blog post tagging system
Database Tables:
post_tag tagsposts
Database structure
posts table:
id mediumint autoincrement unsigned
title varchar(1000)
body text
tags table:
id mediumint autoincrement unsigned
name varchar(1000)
Database structure
post_tag: (pivot table)
id mediumint autoincrement unsigned
post_id mediumint
tag_id mediumint
Case study: blog post tagging system
Database Tables:
post_tag tagsposts
Eloquent Models use convention over configuration:
Post Tag
Laravel manages singular/plural, so be careful:
echo str_plural('mouse');
mice
echo str_singular('media');
medium
echo str_plural('prognosis');
prognoses
Post Model
<?php
Class Post extends Eloquent {
}
Tag Model
<?php
Class Tag extends Eloquent {
}
Post Model with relation
<?php
Class Post extends Eloquent {
public function tags()
{
return $this->belongsToMany('Tag');
}
}
Eloquent methods
$post = Post::find(1);
$tags = $post->tags;
$tags:
{
"tags" : [{"id": "10", "name": "Sicily"},{"id": "16", "name":
"Tourism"}]
}
Resource Controller
Represents the C part of the MVC
● Allows us to easily create RESTful APIs using models
● Handles routing for GET, PUT/PATCH, POST, DELETE
CRUDL
action: HTTP verb: path:
Create POST /posts
Read GET /posts/id
Update PUT/PATCH /posts/id
Delete DELETE /posts/id
List GET /posts
Artisan CLI
Laravel’s command line interface tool that performs basic
development tasks.
● Perform migrations
● Create resource controllers
● Other great tasks
$ php artisan controller:make PostsController
Let’s create our controller for 'Post' model:
/app/controllers/PostsController.php
Route::resource('posts',
'PostsController');
Let’s add the route for the 'Post' Controller to the routes.php file:
/app/controllers/PostsController.php
<?php
PostsController extends BaseController {
public function index(){
}
public function store(){
}
public function show($id){
}
public function update($id){
}
public function destroy($id){
}
}
Here’s what gets created:
// Create POST http://api.domain.com/posts
public function store()
{
$post = new Post;
$post->title = Input::get('title');
$post->body = Input::get('body');
$post->save();
return Response::make(['id'=>$post->id],201);
}
CRUDL “New post”
CRUDL “Post: find id”
// Read GET http://api.domain.com/posts/{id}
public function show($id)
{
return Post::find($id);
}
returns:
{
"id": 23,
"title": "Nice beaches In Italy",
"body": "....."
}
public function show($id)
{
return Post::with('tags')->find($id);
}
returns:
{
"id" : "23",
"title" : "Nice beaches In Italy",
"body" : ".....",
"tags" : [{ "name": "Sicily" }...]
}
CRUDL “Post: find id with tags”
public function show($id)
{
return Post::with('tags') ->remember(240) ->find($id);
}
Need caching?
// Create POST
// http://api.domain.com/posts
public function store()
{
$post = new Post;
$post->title = Input::get('title');
$post->body = Input::get('body');
$post->save();
return Response::make(['id'=>$post->id],201);
}
// Update PUT/PATCH
// http://api.domain.com/posts/{id}
public function update($id)
{
$post = Post::find($id);
$post->title = Input::get('title');
$post->body = Input::get('body');
$post->save();
return Response::make($post, 200);
}
CRUDL
// Delete DELETE http://api.domain.com/posts/{id}
public function destroy($id) {
$post = Post::find($id);
$post->delete();
return Response::make('',204);
}
CRUDL
CRUDL
// List GET http://api.domain.com/posts
public function index()
{
return Post::all();
}
returns:
[{ "id" : "23", "title" : "Nice beaches In Italy", "body" : "....."},
{ "id" : "24", "title" : "Visiting Erice", "body" : "....."},
{ "id" : "25", "title" : "Beautiful Taormina", "body" : "....."},
...
]
Need Authentication?
Route::resource('posts', 'PostController') ->before('auth');
filters.php:
Route::filter('auth', function()
{
if (Auth::guest()){
return Response::make('', 401);
}
});
Need OAuth2?
lucadegasperi/oauth2-server-laravel
Grazie mille -- Thank you very much

More Related Content

What's hot

Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5Bukhori Aqid
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Vikas Chauhan
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web ArtisansRaf Kewl
 
Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoitTitouan BENOIT
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialAdventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialJoe Ferguson
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Viral Solani
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In DepthKirk Bushell
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with LaravelMichael Peacock
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.SWAAM Tech
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Vikas Chauhan
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5Darren Craig
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design PatternsBobby Bouwmann
 
Hello World on Slim Framework 3.x
Hello World on Slim Framework 3.xHello World on Slim Framework 3.x
Hello World on Slim Framework 3.xRyan Szrama
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentationToufiq Mahmud
 

What's hot (20)

Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Rest api titouan benoit
Rest api   titouan benoitRest api   titouan benoit
Rest api titouan benoit
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 TutorialAdventures in Laravel 5 SunshinePHP 2016 Tutorial
Adventures in Laravel 5 SunshinePHP 2016 Tutorial
 
Intro to Laravel
Intro to LaravelIntro to Laravel
Intro to Laravel
 
Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)Introduction to Laravel Framework (5.2)
Introduction to Laravel Framework (5.2)
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
 
Workshop Laravel 5.2
Workshop Laravel 5.2Workshop Laravel 5.2
Workshop Laravel 5.2
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
 
Laravel Design Patterns
Laravel Design PatternsLaravel Design Patterns
Laravel Design Patterns
 
Hello World on Slim Framework 3.x
Hello World on Slim Framework 3.xHello World on Slim Framework 3.x
Hello World on Slim Framework 3.x
 
Laravel presentation
Laravel presentationLaravel presentation
Laravel presentation
 

Viewers also liked

Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Ryan Cuprak
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
Online Video: How It Changes & Enhances The Way We Learn
Online Video: How It Changes & Enhances The Way We LearnOnline Video: How It Changes & Enhances The Way We Learn
Online Video: How It Changes & Enhances The Way We LearnLinkedIn Learning Solutions
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravelwajrcs
 
How to score in exams with little prepration
How to score in exams with little preprationHow to score in exams with little prepration
How to score in exams with little preprationTrending Us
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksPhill Sparks
 
Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?John Blackmore
 
9 Learning Strategies from Knowledge to Know-How
9 Learning Strategies from Knowledge to Know-How9 Learning Strategies from Knowledge to Know-How
9 Learning Strategies from Knowledge to Know-HowLinkedIn Learning Solutions
 

Viewers also liked (9)

Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
Hybrid Mobile Development with Apache Cordova and Java EE 7 (JavaOne 2014)
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Online Video: How It Changes & Enhances The Way We Learn
Online Video: How It Changes & Enhances The Way We LearnOnline Video: How It Changes & Enhances The Way We Learn
Online Video: How It Changes & Enhances The Way We Learn
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Domain Driven Design using Laravel
Domain Driven Design using LaravelDomain Driven Design using Laravel
Domain Driven Design using Laravel
 
How to score in exams with little prepration
How to score in exams with little preprationHow to score in exams with little prepration
How to score in exams with little prepration
 
Software Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill SparksSoftware Design Patterns in Laravel by Phill Sparks
Software Design Patterns in Laravel by Phill Sparks
 
Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?Digpen 7: Why choose Laravel?
Digpen 7: Why choose Laravel?
 
9 Learning Strategies from Knowledge to Know-How
9 Learning Strategies from Knowledge to Know-How9 Learning Strategies from Knowledge to Know-How
9 Learning Strategies from Knowledge to Know-How
 

Similar to RESTful API development in Laravel 4 - Christopher Pecoraro

CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
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
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction PresentationNerd Tzanetopoulos
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php PresentationAlan Pinstein
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolmentRajib Ahmed
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestJoshua Warren
 
Plugin development demystified 2017
Plugin development demystified 2017Plugin development demystified 2017
Plugin development demystified 2017ylefebvre
 
Getting started with WordPress development
Getting started with WordPress developmentGetting started with WordPress development
Getting started with WordPress developmentSteve Mortiboy
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Mike Schinkel
 
iOS Swift application architecture
iOS Swift application architectureiOS Swift application architecture
iOS Swift application architectureRomain Rochegude
 
Php Interview Questions
Php Interview QuestionsPhp Interview Questions
Php Interview QuestionsUmeshSingh159
 
Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answerssheibansari
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 
How to upload Laravel Project on Shared Hosting With CPanel.pdf
How to upload Laravel Project on Shared Hosting With CPanel.pdfHow to upload Laravel Project on Shared Hosting With CPanel.pdf
How to upload Laravel Project on Shared Hosting With CPanel.pdfHost It Smart
 

Similar to RESTful API development in Laravel 4 - Christopher Pecoraro (20)

CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
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...
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
New PHP Exploitation Techniques
New PHP Exploitation TechniquesNew PHP Exploitation Techniques
New PHP Exploitation Techniques
 
Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
 
Behavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWestBehavior & Specification Driven Development in PHP - #OpenWest
Behavior & Specification Driven Development in PHP - #OpenWest
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
Plugin development demystified 2017
Plugin development demystified 2017Plugin development demystified 2017
Plugin development demystified 2017
 
Oop's in php
Oop's in php Oop's in php
Oop's in php
 
Getting started with WordPress development
Getting started with WordPress developmentGetting started with WordPress development
Getting started with WordPress development
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
iOS Swift application architecture
iOS Swift application architectureiOS Swift application architecture
iOS Swift application architecture
 
Php Interview Questions
Php Interview QuestionsPhp Interview Questions
Php Interview Questions
 
Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answers
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
How to upload Laravel Project on Shared Hosting With CPanel.pdf
How to upload Laravel Project on Shared Hosting With CPanel.pdfHow to upload Laravel Project on Shared Hosting With CPanel.pdf
How to upload Laravel Project on Shared Hosting With CPanel.pdf
 

Recently uploaded

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
 
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.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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
 
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 CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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 🔝✔️✔️Delhi Call girls
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
+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
 
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
 
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.jsAndolasoft Inc
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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...panagenda
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Recently uploaded (20)

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 ...
 
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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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 🔝✔️✔️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+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...
 
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
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

RESTful API development in Laravel 4 - Christopher Pecoraro

  • 1. RESTful API development in Laravel 4 Christopher Pecoraro phpDay 2014 Verona, Italy May 16th-17th, 2014
  • 2. I was born in 1976 in Pittsburgh, Pennsylvania, USA.
  • 3. I have been living in Mondello, Sicily since 2009.
  • 4. Two households both alike in dignity…
  • 11. the first integrated viral media company
  • 12. Laravel A PHP 5.3 PHP 5.4 framework Laravel Version Minimum PHP version required 4.0 5.3 4.1 5.3 4.2 5.4 Upgrade to at least PHP 5.4, if not PHP 5.5: Trust Rasmus and Lorna Jane In fair Verona, where we lay our scene…
  • 13. Worldwide growth in Google search from January 2012 - Present
  • 14. Laravel takes advantage of the Facade pattern: Input::get('foo');
  • 15. Installing Laravel ● Download: http://laravel.com/laravel.phar ● sudo apt-get install php5-mcrypt ● Rename laravel.phar to laravel and move it to /usr/local/bin ● laravel new blog ("blog" is the project name in this case.) ● chmod -R 777 app/storage
  • 16. Installing Laravel Other options: ● Download a Laravel Vagrant box. ● Use forge.laravel.com: ○ Deploy a box with PHP 5.5, Hack (Beta), and HHVM ○ Tuned specifically for Laravel on Digital Ocean, RackSpace, etc.
  • 17. Laravel has an expressive syntax, easing common tasks such as: ● authentication ● routing ● sessions ● caching Laravel combines aspects of other frameworks such as: ● Ruby on Rails (active record) ● ASP.NET MVC Laravel features: ● inversion of control (IoC) container ● database migration ● unit testing support (PHPUnit)
  • 18. Laravel application structure Important files and directories: /app /models /controllers /views routes.php filters.php /public (assets such as javascript, css files) /config (settings for database drivers, smtp, etc.)
  • 19. Relevant Terms: ● Eloquent ORM ● Artisan CLI ● Resource Controller
  • 20. Eloquent ORM Acts as the M (model) part of MVC ● It allows developers to use an object-oriented approach. ● Interacts with database tables by representing them as models.
  • 21. Case study: blog post tagging system Database Tables: post_tag tagsposts
  • 22. Database structure posts table: id mediumint autoincrement unsigned title varchar(1000) body text tags table: id mediumint autoincrement unsigned name varchar(1000)
  • 23. Database structure post_tag: (pivot table) id mediumint autoincrement unsigned post_id mediumint tag_id mediumint
  • 24. Case study: blog post tagging system Database Tables: post_tag tagsposts Eloquent Models use convention over configuration: Post Tag
  • 25. Laravel manages singular/plural, so be careful: echo str_plural('mouse'); mice echo str_singular('media'); medium echo str_plural('prognosis'); prognoses
  • 26. Post Model <?php Class Post extends Eloquent { }
  • 27. Tag Model <?php Class Tag extends Eloquent { }
  • 28. Post Model with relation <?php Class Post extends Eloquent { public function tags() { return $this->belongsToMany('Tag'); } }
  • 29. Eloquent methods $post = Post::find(1); $tags = $post->tags; $tags: { "tags" : [{"id": "10", "name": "Sicily"},{"id": "16", "name": "Tourism"}] }
  • 30. Resource Controller Represents the C part of the MVC ● Allows us to easily create RESTful APIs using models ● Handles routing for GET, PUT/PATCH, POST, DELETE
  • 31. CRUDL action: HTTP verb: path: Create POST /posts Read GET /posts/id Update PUT/PATCH /posts/id Delete DELETE /posts/id List GET /posts
  • 32. Artisan CLI Laravel’s command line interface tool that performs basic development tasks. ● Perform migrations ● Create resource controllers ● Other great tasks
  • 33. $ php artisan controller:make PostsController Let’s create our controller for 'Post' model: /app/controllers/PostsController.php
  • 34. Route::resource('posts', 'PostsController'); Let’s add the route for the 'Post' Controller to the routes.php file: /app/controllers/PostsController.php
  • 35. <?php PostsController extends BaseController { public function index(){ } public function store(){ } public function show($id){ } public function update($id){ } public function destroy($id){ } } Here’s what gets created:
  • 36. // Create POST http://api.domain.com/posts public function store() { $post = new Post; $post->title = Input::get('title'); $post->body = Input::get('body'); $post->save(); return Response::make(['id'=>$post->id],201); } CRUDL “New post”
  • 37. CRUDL “Post: find id” // Read GET http://api.domain.com/posts/{id} public function show($id) { return Post::find($id); } returns: { "id": 23, "title": "Nice beaches In Italy", "body": "....." }
  • 38. public function show($id) { return Post::with('tags')->find($id); } returns: { "id" : "23", "title" : "Nice beaches In Italy", "body" : ".....", "tags" : [{ "name": "Sicily" }...] } CRUDL “Post: find id with tags”
  • 39. public function show($id) { return Post::with('tags') ->remember(240) ->find($id); } Need caching?
  • 40. // Create POST // http://api.domain.com/posts public function store() { $post = new Post; $post->title = Input::get('title'); $post->body = Input::get('body'); $post->save(); return Response::make(['id'=>$post->id],201); } // Update PUT/PATCH // http://api.domain.com/posts/{id} public function update($id) { $post = Post::find($id); $post->title = Input::get('title'); $post->body = Input::get('body'); $post->save(); return Response::make($post, 200); } CRUDL
  • 41. // Delete DELETE http://api.domain.com/posts/{id} public function destroy($id) { $post = Post::find($id); $post->delete(); return Response::make('',204); } CRUDL
  • 42. CRUDL // List GET http://api.domain.com/posts public function index() { return Post::all(); } returns: [{ "id" : "23", "title" : "Nice beaches In Italy", "body" : "....."}, { "id" : "24", "title" : "Visiting Erice", "body" : "....."}, { "id" : "25", "title" : "Beautiful Taormina", "body" : "....."}, ... ]
  • 43. Need Authentication? Route::resource('posts', 'PostController') ->before('auth'); filters.php: Route::filter('auth', function() { if (Auth::guest()){ return Response::make('', 401); } }); Need OAuth2? lucadegasperi/oauth2-server-laravel
  • 44. Grazie mille -- Thank you very much