$30 off During Our Annual Pro Sale. View Details »

Intro to Laravel 5

Ben Edmunds
September 30, 2016

Intro to Laravel 5

Learn why this new framework has been taking the PHP world by storm.

Are you ashamed to admit you're a PHP developer? Have you been using the same old, boring PHP framework for years? Tired of your PHP applications turning into enormous beasts? Maybe you've heard about Laravel but haven't made the effort to dive into it? In this presentation, we'll walk through what makes Laravel an elegant, fun, and exciting framework to make PHP applications that you'll be proud of.

Ben Edmunds

September 30, 2016
Tweet

More Decks by Ben Edmunds

Other Decks in Technology

Transcript

  1. A PHP Framework For Web Artisans

    View Slide

  2. Ben Edmunds
    @benedmunds
    http://benedmunds.com
    Who is this guy?

    View Slide

  3. Ben Edmunds
    Open Source
    Author
    PHP Town Hall Podcast
    CTO at Mindfulware
    Who is this guy?

    View Slide

  4. What is it?
    PHP Web Framework
    Full-stack
    (what does that even mean anymore)
    Open Source

    View Slide

  5. Who’s behind it?
    Taylor Otwell
    @taylorotwell

    View Slide

  6. I already use X. Why should I use Laravel?

    View Slide

  7. Why use it?
    Expressive Syntax
    Route::get(‘user/{id}’, function($id)
    {
    $user = User::find($id);
    return view(‘home')
    ->with('user', $user);
    });

    View Slide

  8. Why use it?
    Utilizes the latest PHP features
    Namespaces
    PSR-4 Autoloading
    Interfaces
    IoC

    View Slide

  9. Why use it?
    Service Providers
    De-Coupled
    Flexible
    DRY
    Event Handling

    View Slide

  10. Why use it?
    Contracts = Groups of Interfaces
    Loose Coupling
    Testability
    Explicit
    Flexible

    View Slide

  11. Why use it?
    Facades = Quick Start
    $object = new class;
    $object->set('key', 'value');
    Class::set('key', 'value');

    View Slide

  12. Why use it?
    Well Documented
    http://laravel.com/docs

    View Slide

  13. Why use it?
    Artisan CLI Tool
    $ php artisan migrate

    View Slide

  14. Why use it?
    Built on Composer
    http://packagist.com
    Entirely Modular
    PSR-2, PSR-3, PSR-4, PSR-7
    Compliant

    View Slide

  15. Why use it?
    Test Coverage
    Focus on Testable Code

    View Slide

  16. Why use it?
    Full Stack Framework
    Full Stack Ecosystem

    View Slide

  17. Why use it?
    Homestead
    Pre-made Vagrant Box
    Nginx
    MySQL/PostgreSQL
    Beanstalkd
    Redis
    Memcached
    PHP / HHVM
    Node

    View Slide

  18. Why use it?
    PAAS to quickly deploy PHP apps to the “cloud”
    Digital Ocean
    Linode
    AWS

    View Slide

  19. Why use it?
    Full application quick start
    Authentication
    Teams
    Billing
    SASS-y

    View Slide

  20. Let’s do some comparisons

    View Slide

  21. Comparison
    MVC Design
    Lightweight
    Fast
    Excellent Docs
    Compatibility
    Technical Debt

    View Slide

  22. Comparison
    MVC Design
    Heavy but has Silex
    Slow-ish
    Complex
    Good Docs
    Modular
    Backed by SensioLabs

    View Slide

  23. Beyond MVC Design
    Easy to get started
    Consistent/Stable
    Fast
    Excellent Docs
    Threw out previous
    framework ideas and
    started over
    Comparison

    View Slide

  24. OK, I’ll try it. How do I get started?

    View Slide

  25. Download
    Composer Based Install
    $ composer create-project
    laravel/laravel --prefer-dist

    View Slide

  26. Structure
    Commands
    Providers
    Controller || Route || Both
    Middleware
    Services
    Views
    Model / Repository / FLEXIBILITY

    View Slide

  27. Routes

    View Slide

  28. Routes
    Create routes at:
    routes/web.php
    routes/api.php
    Web = web middleware
    API = api middleware
    App\Providers\RouteServiceProvider to add new route files

    View Slide

  29. Routes
    What methods are available:
    Route::get();
    Route::post();
    Route::put();
    Route::patch();
    Route::delete();
    Route::any(); //all of the above

    View Slide

  30. Routes
    Register multiple verbs for a single route:
    Router::match([‘get’, ‘post’], ‘/’, function(){
    //this will run for both GET and POST
    });

    View Slide

  31. Routes
    routes/web.php
    Route::get('/', function(){
    echo ‘Boom!’;
    });

    View Slide

  32. Testing

    View Slide

  33. Testing
    Runs all tests located at:
    /tests/
    $ php artisan test

    View Slide

  34. Testing
    routes/web.php
    Route::get('/', function(){
    echo ‘Boom!’;
    });

    View Slide

  35. Testing
    /tests/ExampleTest.php
    Test it! Test it good!
    class ExampleTest extends TestCase {
    function testBasicExample()
    {
    $this->visit('/')
    ->see(‘Boom!');

    View Slide

  36. Testing
    $ php artisan test
    Run it!
    PHPUnit 3.6.10 by Sebastian Bergmann.
    Configuration read from ...
    Time: 0 seconds, Memory: 6.25Mb
    OK (1 test, 1 assertion)
    Output

    View Slide

  37. API?

    View Slide

  38. What about an API? Routes to the rescue!

    View Slide

  39. API
    routes/api.php
    Route::get(‘user/{id}’, function($id){
    return json_encode([
    ‘user‘ => User::find($id),
    ‘success‘ => true
    ]);
    });

    View Slide

  40. API
    routes/api.php
    Route::get(‘user/{id}’, function($id){
    return [
    ‘user‘ => User::find($id),
    ‘success‘ => true
    ];
    });

    View Slide

  41. API
    App\Providers\RouteServiceProvider
    protected function mapApiRoutes() {
    Route::group([
    'middleware' => ['api', 'auth:api'],
    'namespace' => $this->namespace,
    'prefix' => 'api',
    ], function ($router) {
    require base_path('routes/api.php');
    });

    View Slide

  42. API
    App\Providers\RouteServiceProvider
    protected function mapApiRoutes() {
    Route::group([
    'middleware' => ['api', 'auth:api'],
    'namespace' => $this->namespace,
    'prefix' => 'api',
    ], function ($router) {
    require base_path('routes/api.php');
    });

    View Slide

  43. API
    /tests/api/UserTest.php
    class UserTest extends TestCase {
    public function testGetUser()
    {
    $this->get(‘/api/user/1’)
    ->seeJson([
    ‘success‘ => true
    ]);

    View Slide

  44. Controllers

    View Slide

  45. Controllers
    OK, routes are cool and all, but
    what if I want to use controllers?

    View Slide

  46. Controllers
    routes/web.php
    Route::post('status', 'StatusController@create');
    class StatusController extends Controller {
    public function create(Request $request)
    {

    app/Http/controllers/StatusController.php

    View Slide

  47. Shit just got real

    View Slide

  48. Middleware

    View Slide

  49. Middleware
    Route Filters
    BETTER FASTER STRONGER
    Middleware!

    View Slide

  50. Middleware
    Popular Uses:
    Auth
    ACL
    Session
    Caching
    Debug
    Logging
    Analytics
    Rate Limiting

    View Slide

  51. Middleware
    Route::post('status',
    ‘StatusController@create’,
    [‘middleware’ => ‘auth’]
    );

    View Slide

  52. Middleware
    Route::post('status',
    ‘StatusController@create’,
    [‘middleware’ => [
    ‘first’,
    ‘second’,
    ‘third’,
    ]]
    );

    View Slide

  53. Middleware
    class AjaxMiddleware implements Middleware {
    public function handle($request, Closure $next)
    {
    if (!$request->ajax())
    return response('Unauthorized.', 401);
    return $next($request);
    }

    View Slide

  54. Middleware
    Groups for DRY routing:
    Route::group(['middleware' => 'auth'], function(){
    Route::get('/statuses', function(){

    });

    View Slide

  55. Database

    View Slide

  56. Database
    Query Builder
    Eloquent ORM
    Migrations
    Seeding

    View Slide

  57. Query Builder
    Simple and Easy to Understand
    Used extensively by Eloquent ORM

    View Slide

  58. Query Builder
    $user = DB::table('statuses')
    ->where(‘email’, '[email protected]’)
    ->first();
    Query Row by Email

    View Slide

  59. Query Builder
    $id = DB::table('statuses')
    ->insertGetId([
    ‘user_id' => 1,
    'email' => ‘[email protected]',
    'text' => ‘Vegas Baby! #zendcon’,
    ]);
    Insert & Get ID

    View Slide

  60. Eloquent ORM
    Simple
    Expressive
    Efficient

    View Slide

  61. Eloquent ORM
    use Illuminate\Database\Eloquent\Model;
    class Status extends Model {
    }
    Define an Eloquent model

    View Slide

  62. Eloquent ORM
    $status =
    App\Status::where(‘user_id’, 1)
    ->first();
    Simple query

    View Slide

  63. Eloquent ORM
    $statuses =
    App\Status::where(‘views', '>', 100)
    ->get();
    Slightly more advanced query

    View Slide

  64. Eloquent ORM
    Relationships
    class Status extends Model {
    public function user()
    {
    return $this->belongsTo(‘App\User');
    }
    }
    App\Status::find(1)->user->email;
    Retrieve Status Creator Email

    View Slide

  65. Eloquent ORM
    Normal Usage
    $statuses = App\Status::all();
    foreach ($statuses as $status)
    echo $status->user->email;

    View Slide

  66. Eloquent ORM
    Normal Usage
    $statuses = App\Status::all();
    foreach ($statuses as $status)
    echo $status->user->email;
    SELECT * FROM "statuses"
    foreach result {
    SELECT * FROM "users" WHERE "id" = 1
    }
    100 statuses = 101 queries

    View Slide

  67. WTF!? ORMs Suck!

    View Slide

  68. Eloquent ORM
    $statuses =
    App\Status::with(‘user’)->get();
    foreach ($statuses as $status)
    echo $status->user->email;
    Eager Loading FTW!

    View Slide

  69. Eloquent ORM
    $statuses =
    App\Status::with(‘user’)->get();
    foreach ($statuses as $status)
    echo $status->user->email;
    100 statuses = 2 queries
    SELECT * FROM "statuses"
    SELECT * FROM "users" WHERE "id" IN (1, 2, 3, 4, 5, ...)
    Eager Loading FTW!

    View Slide

  70. Eloquent ORM
    creating
    created
    updating
    updated
    saving
    saved
    deleting
    deleted
    restoring
    restored
    Events

    View Slide

  71. Views

    View Slide

  72. Views
    Route::get('/', function(){
    return view('home.index');
    //resources/views/home/index.blade.php
    });
    Returning a view from a route

    View Slide

  73. Views
    Route::get('/', function(){
    return view(‘home.index')
    ->with('email', '[email protected]');
    Sending data to a view

    View Slide

  74. Views
    Sending data to a view with magic methods
    Route::get('/', function(){
    $view = view('home.index');
    $view->email = ‘[email protected]’;
    return $view;

    View Slide

  75. Views
    Blade Templates
    Email Address:
    {{ $email }}

    View Slide

  76. Views
    Blade Templates
    Email Address:
    {{ $email or ‘Please enter email’ }}

    View Slide

  77. Views
    Blade Templates
    @include(‘user.registration’)

    View Slide

  78. Echo

    View Slide

  79. Echo
    Web sockets made easy
    php artisan make:event MessageReceived
    /app/Events/MessageReceived.php

    View Slide

  80. Echo
    Pusher JS
    or
    Socket.io

    View Slide

  81. Cashier

    View Slide

  82. Cashier
    Simple Payment Management
    Stripe
    Braintree

    View Slide

  83. Scout

    View Slide

  84. Scout
    API Authentication
    JWT
    OAuth 2
    Laravel and Vue JS

    View Slide

  85. Form Requests

    View Slide

  86. Form Requests
    Designed just for form handling/validation
    class CreateStatusRequest extends FormRequest
    {
    public function rules() {
    return [
    ‘email’ => ‘required|email',
    ‘text' => ‘required',
    ];
    }

    View Slide

  87. Form Requests
    class StatusController extends Controller {
    public function create(CreateStatusRequest $request){

    }

    View Slide

  88. Facades

    View Slide

  89. Facades
    $var = Session::get('foo');
    Resolves behind the scenes
    Getting a session variable

    View Slide

  90. Facades
    Controller Injection to the rescue!
    Managing Class Responsibilities?

    View Slide

  91. Facades
    class HomeController extends Controller {
    public function __construct(Request $request){
    $value = $request->session()->get('key');
    }
    Controller Injection

    View Slide

  92. Drama
    Da da DOM

    View Slide

  93. That’s a Wrap
    Utilizes the best PHP has to offer
    Well designed API with great docs
    Ready to scale architecture
    Go make cool things and have fun

    View Slide

  94. Community
    http://github.com/laravel/laravel
    http://docs.laravel.com
    http://forums.laravel.com

    View Slide

  95. Resources
    Dayle Rees - Code Smart
    Laravel: From Apprentice to Artisan
    LaraCasts

    View Slide

  96. Securing PHP Apps
    SecuringPhpApps.com
    Resources

    View Slide

  97. THANKS!
    Ben Edmunds
    @benedmunds
    http://benedmunds.com
    https://joind.in/talk/62c46

    View Slide