Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Laravel - The PHP Framework for Web Artisans - A Quick Tour

Sidnet
November 27, 2015

Laravel - The PHP Framework for Web Artisans - A Quick Tour

Created and presented by Mariusz Kalota.

Sidnet

November 27, 2015
Tweet

More Decks by Sidnet

Other Decks in Programming

Transcript

  1. Laravel 5 The PHP Framework for Web Artisans (A Quick

    Tour) Mariusz Kalota Nov 27, 2015
  2. PHP Frameworks • So many to choose from! • If

    GitHub stars can be considered a measurement of popularity, then...
  3. Repository stars on GitHub (Nov 16, 2015) 0 2000 4000

    6000 8000 10000 12000 14000 16000 18000 20000
  4. About the Framework • Author: Taylor Otwell • Initial release:

    June 2011 • Stable release: version 5.1.24 (Nov 11, 2015) • Architecture: MVC • License: MIT
  5. About the Framework Laravel 5.1 is the first release of

    Laravel to receive long-term support (LTS), with planned availability of bug fixes for two years and security patches for three years. LTS versions of Laravel are planned to be released every two years.
  6. Server Requirements • PHP >= 5.5.9 • OpenSSL PHP Extension

    • PDO PHP Extension • Mbstring PHP Extension • Tokenizer PHP Extension
  7. Installation – Composer • First, get the Laravel installer using

    Composer: • Create a fresh Laravel installation: • Create a new project: composer global require "laravel/installer=~1.1" laravel new blog composer create-project laravel/laravel --prefer-dist
  8. Installation – Cloning from GitHub • Clone the GitHub repository:

    • Rename .env.example to .env • Install dependencies: • Generate encryption key: php artisan key:generate composer install git clone https://github.com/laravel/laravel
  9. Artisan Console • Artisan is a command-line utility included with

    Laravel • Provides helpful commands for common tasks during application development • Can be extended with custom commands specific to the application php artisan list
  10. Artisan Console – Commands • down Enable maintenance mode •

    up Disable maintenance mode • tinker Interact with the application • route:list List all registered routes
  11. Artisan Console – Commands • make:{something} Create a new {something}

    class • vendor:publish Publish assets from vendor packages
  12. Database Migrations Migrations are an easy way to make changes

    to the application's database schema, kind of like version control works for source code.
  13. Database Migrations • Create a new migration, using the Artisan

    make:migration command: • The newly added migration will be placed in the database/migrations directory • The timestamp in the file name allows Laravel to determine the order of the migrations php artisan make:migration create_users_table
  14. Database Migrations – Structure • A migration class contains two

    methods: up and down. public function up() { Schema::create('items', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } public function down() { Schema::drop('items'); }
  15. Database Migrations – Running • Running all outstanding migrations: •

    Rollback of the most recent migration: • Rollback of all migrations: • A single command to rollback/migrate: php artisan migrate php artisan migrate:rollback php artisan migrate:reset php artisan migrate:refresh
  16. Database Migrations – Running • To run all outstanding migrations,

    use the Artisan command: • To rollback the latest migration "operation", you may use the rollback command: • To rollback all migrations, use the command: • Rollback / Migrate in single command: php artisan migrate php artisan migrate:rollback php artisan migrate:reset php artisan migrate:refresh
  17. Routing • Basic routing methods: get(), post(), put(), delete(), match(),

    any() Route::get('/', function () { return 'Hello World'; }); Route::post('foo/bar', function () { return 'Hello World'; });
  18. Routing • Route parameters: • Optional parameters: Route::get('items/{id}', function ($id)

    { return 'Item ' . $id; }); Route::get('beverages/{name?}', function($name = 'Beer') { ... } );
  19. Routing • Route groups: Route::group( [ 'middleware' => 'auth', 'prefix'

    => 'admin' ], function () { Route::get('/dashboard', 'DashboardController@index'); Route::get('/settings', 'SettingsController@index'); } );
  20. Middleware Middleware is a useful mechnism which allows for filtering

    of HTTP requests processed by the web application.
  21. Middleware • Creating a new middleware: php artisan make:middleware AdultMiddleware

    class AdultMiddleware { public function handle($request, Closure $next) { if ($request->input('age') < 18) { return redirect('forbidden'); } return $next($request); } }
  22. Middleware • Adding a middleware to App/Http/Kernel.php's $middleware property causes

    it to be run during every request • Before a middleware can be assigned to routes, it needs a short-hand identifier in App/Http/Kernel.php: protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, ... ];
  23. Controllers • Creating a controller using Artisan: • Creating an

    empty controller class: php artisan make:controller NewController php artisan make:controller NewController --plain
  24. Controllers Creating URLs to controller actions • Named controller route:

    • With controller class and method names: $url = route('name'); $url = action('SomeController@method'); $url = action('SomeController@method', [ 'id' => 42 ]);
  25. Views • Stored in the resources/views directory • Made with

    plain HTML/PHP or Blade template system <html> <body> <h1>Hello, <?php echo $name; ?></h1> </body> </html>
  26. Views • The global view helper function returns a view

    return view('admin.dashboard', [ 'name' => 'Alice' ]); return view('hello')->with('name', 'Alice');
  27. Views – Blade Templates • Blade views use the .blade.php

    extension • Two of the primary benefits of using Blade are template inheritance and sections
  28. Views – Blade Templates <html> <head> <title>SomeApp - @yield('title')</title> </head>

    <body> @section('sidebar') Sidebar content goes here @show <div class="main"> @yield('content') </div> </body> </html>
  29. Views – Blade Templates • Extending a layout @extends('layouts.master') @section('title',

    'Page Title') @section('sidebar') @parent <p>Some more content that goes in the sidebar</p> @endsection @section('content') <p>This is the main page content.</p> @endsection
  30. Views – Blade Templates • Variables wrapped in curly braces

    will have the htmlentities() function applied to them: • Unescaped data is displayed using !!: • The @ symbol is used to have the Blade engine skip an expression: Hello, {{ $name }}. Hello, {!! $name !!}. Hello, @{{ name }}.
  31. Views – Blade Templates • If statements: @include('view.name', ['name' =>

    'value']) @if (count($results) === 1) One search result found. @elseif (count($results) > 1) Multiple search results found. @else No results found. @endif @unless (Auth::check()) Not logged in. @endunless
  32. Views – Blade Templates • Loops: @for ($i = 1;

    $i <= 10; $i++) Current index: {{ $i }} @endfor @foreach ($items as $item) Processing item {{ $item->id }} @endforeach @forelse ($results as $result) <li>{{ $result->title }}</li> @empty <p>No search results</p> @endforelse
  33. Models – Eloquent ORM • Models are stored in the

    app directory • Created with the make:model Artisan command: • By default, the database table name is the snake_case, plural name of the class. This can be overridden with the $table property: php artisan make:model Account protected $table = 'user_accounts';
  34. Models – Eloquent ORM • Eloquent will also assume that

    there's a primary key column named id in each table. This may be overridden using the $primaryKey property.
  35. Models – Eloquent ORM • Retrieving multiple models: • Retrieving

    multiple models with additional constraints using Query Builder methods: $items = Item::all(); $items = App\Item::where('status', 'available') ->orderBy('quantity', 'desc') ->take(5) ->get();
  36. Models – Eloquent ORM • Retrieving a single model by

    its primary key: • Retrieving the first model matching the given constraints: $flight = App\Flight::find(1); $flight = App\Flight::where('active', 1)->first();
  37. Models – Eloquent ORM • To prevent mass-assignment vulnerabilities, models

    set the $fillable or $guarded attribute: • Creating new models using the create() method: protected $fillable = ['name']; $account = App\Account::create(['name' => 'foo']); $account = App\Account::create($request->all()); protected $guarded = ['id'];
  38. Models – Eloquent ORM • Other creation methods: $user =

    App\User::firstOrCreate(['name' => 'test']); $user = App\User::firstOrNew(['name' => 'test']);
  39. Models – Eloquent ORM • Deleting a model using its

    delete method: • Deleting an existing model by key: • Deleting models using a query: $item = App\Item::find(1); $item->delete(); App\Item::destroy(1); App\Item::destroy([1, 2, 3]); App\Item::destroy(1, 2, 3); $deletedRows = App\Item::where('quantity', 0)->delete();
  40. Eloquent: Relationships – One to One • Defining a one

    to one relationship: • Retrieving the related record: public function address() { return $this->hasOne('App\Address'); } return $this->hasOne('App\Address', 'foreign_key', 'local_key'); $address = User::find(1)->address;
  41. Eloquent: Relationships – One to One • Defining the inverse

    of the relation: public function user() { return $this->belongsTo('App\User'); } return $this->belongsTo('App\User', 'foreign_key', 'local_key');
  42. Eloquent: Relationships – One to Many • Defining the relationship:

    • Retrieving the related records: public function posts() { return $this->hasMany('App\Post'); } return $this->hasMany('App\Post', 'foreign_key', 'local_key'); $posts = Blog::find(1)->posts;
  43. Eloquent: Relationships – One to Many • Defining the inverse

    of the relation: public function blog() { return $this->belongsTo('App\Blog'); } return $this->belongsTo('App\Blog', 'foreign_key', 'other_key');
  44. Eloquent: Relationships – Many to Many • Defining the relationship:

    • Retrieving the related records: public function courses() { return $this->belongsToMany('App\Course'); } return $this->belongsToMany('App\Course', 'student_courses', 'student_id', 'course_id'); $courses = Student::find(1)->courses;
  45. Eloquent: Relationships – Many to Many • Defining the inverse

    of the relation: • Intermediate table columns can be accessed using the pivot attribute: public function students() { return $this->belongsToMany('App\Student'); } echo $course->pivot->created_at;
  46. Collections • Collections of Eloquent models are always returned as

    Collection instances • The Collection class can also be used for any other purpose in the application • Creating a Collection: $collection = collect([1, 2, 3]);
  47. Collections • Collection methods: all() filter() groupBy() last() sort() contains()

    first() has() map() sortBy() count() forget() isEmpty() merge() toArray() each() get() keyBy() search() toJson() and more...
  48. Eloquent: Accessors and Mutators • Defining an accessor: • Defining

    a mutator: public function getNameAttribute($value) { return ucfirst($value); } public function setNameAttribute($value) { $this->attributes['name'] = strtolower($value); }
  49. Eloquent: Accessors and Mutators • Using the $casts attribute, database

    values can be converted into common data types • Supported types: integer, real, float, double, string, boolean, object, array, collection, date and datetime protected $casts = [ 'is_active' => 'boolean', ];
  50. Query Builder • The table() method of the DB facade

    returns a fluent query builder instance • The get() method returns an array of results, each being an instance of the PHP StdClass object: • Retrieving a single row: $items = DB::table('items')->get(); $item = DB::table('items')->first();
  51. Query Builder • Select queries: • Raw expressions: $items =

    DB::table('items') ->select('id as number', 'name')->get(); $items = DB::table('items') ->select(DB::raw('count(*) as stock')) ->get();
  52. Query Builder • Joins: • Unions: ->join('comments', 'posts.id', '=', 'comments.post_id')

    $anon_comments = DB::table('comments') ->whereNull('user_id'); $comments = DB::table('comments') ->whereNull('title') ->union($anon_comments) ->get(); ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  53. Query Builder • Where clauses: $items = DB::table('items')->where('status', 'active') ->get();

    $items = DB::table('items') ->where('quantity', '<', 10) ->orWhere('status', 'inactive') ->get(); $items = DB::table('items') ->where('quantity', '>=', 100) ->get();
  54. Query Builder • Insert queries: • Update queries: • Delete

    queries: DB::table('items')->insert([ ['name' => 'Coffee mug', 'quantity' => 10], ['name' => 'Beer glass', 'quantity' => 20] ]); DB::table('items')->where('id', 1) ->update(['quantity' => 5]); DB::table('items')->where('quantity', '<', 5)->delete();
  55. Requests • Getting a hold of the current HTTP request

    instance in a controller constructor or method: use Illuminate\Http\Request; class ItemController extends Controller { public function store(Request $request) { // ... } }
  56. Requests • Retrieving input: • As a property of the

    Request instance: • With a default value: • Accessing an array element: $title = $request->input('title'); $title = $request->title; $title = $request->input('title', 'New Post'); $name = $request->input('items.0.name');
  57. Requests • Checking if an input value is present: •

    Retrieving all input data: • Flashing input to the session: • Accessing “old” input data: if ($request->has('name')) { ... $input = $request->all(); $request->flash(); $name = $request->old('name');
  58. Requests – Validation • Using the validate() method to validate

    the request in a controller: $this->validate($request, [ 'username' => 'required|unique:users|max:20', 'name' => 'required' ]);
  59. Requests – Validation • Creating a validator instance using the

    Validator facade: $validator = Validator::make($request->all(), [ 'username' => 'required|unique:users|max:20', 'name' => 'required' ]); if ($validator->fails()) { return redirect('users/add') ->withErrors($validator)->withInput(); }
  60. Requests – Validation • „Form requests” contain validation logic •

    Creating a form request class: • Adding validation rules: php artisan make:request StoreItemRequest public function rules() { return [ 'name' => 'required|max:50', 'symbol' => 'required|alpha_num|max:10' ]; }
  61. Requests – Validation • Adding validation messages: public function messages()

    { return [ 'name.required' => 'A name is required', 'symbol.required' => 'A symbol is required' ]; }
  62. Requests – Validation • Authorizing form requests: public function authorize()

    { return Post::where('id', $this->route('post')) ->where('user_id', Auth::id()) ->exists(); } public function authorize() { return true; }
  63. Requests – Validation • Displaying validation errors: <h1>Add Item</h1> @if

    (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
  64. Requests – Validation Some examples of available validation rules: •

    Alpha, Alpha dash, Alpha numeric • Date, Date format • Digits, Digits between, Min, Max, Numeric • Exists, Unique (Database) • Image, MIME types (File) • Required, Required if/unless, Required with
  65. Responses • Basic response: • Response with an additional header:

    • The response helper function: return 'Hello World'; return response($content, $status) ->header('Content-Type', $value); return (new Response($content, $status)) ->header('Content-Type', $value);
  66. Responses • Response with a cookie: • View response: return

    response($content) ->header('Content-Type', $type) ->withCookie('name', 'value'); return response()->view('profile', $data) ->header('Content-Type', $type);
  67. Responses • JSON Response: • JSONP Response: • File Downloads:

    return response()->json(['name' => 'Bob', 'foo' => 1]); return response()->download($path); return response()->download($path, $name, $headers); return response()->json(['name' => 'Bob', 'foo' => 1]) ->setCallback($request->input('cb'));
  68. Redirects • The global redirect helper method: • Redirect the

    user to their previous location: • Redirecting to named routes: • Redirecting to controller actions: return redirect('home/dashboard'); return back()->withInput(); return redirect()->route('user', [1]); return redirect()->action('UserController@show', [1]);
  69. Additional Features • Task Scheduling (CRON) • Authentication System •

    Encryption • Events (simple observer implementation) • Mail (over SwiftMailer library) • Localization
  70. Additional Features • Pagination • “Soft delete” models • A

    collection of “helper” PHP functions (for array operations, URLs, etc.) $users = DB::table('users')->paginate(15);