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

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

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

Symfony2 Introduction Presentation
Symfony2 Introduction PresentationSymfony2 Introduction Presentation
Symfony2 Introduction Presentation
Nerd Tzanetopoulos
 
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
Joshua Warren
 

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

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 

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