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

Introducing Laravel

Introducing Laravel

Originally presented at the PHP Adelaide meetup in June 2017, this talk aims to serve as an introduction to the Laravel Framework and some of its most common and powerful aspects.

The presentation covers many of the fundamental concepts necessary to build an application using Laravel and is suitable for those familiar with PHP in general, but new to the framework.

Michael Dyrynda

June 15, 2017
Tweet

More Decks by Michael Dyrynda

Other Decks in Programming

Transcript

  1. Why a framework? Long ago, in the before /me, developers

    were responsible not only for business logic, but also components common across sites • User authen,ca,on • Input valida,on • Database access • Templa,ng
  2. Why a framework? Today, we have dozens of frameworks and

    thousands of packages and components at our finger9ps. Frameworks like Laravel prepackage these components together and glue them together with things like config files, service providers, and so on. In general, when using a framework, somebody else has made decisions not only about which components to use, but also how they're pieced together.
  3. But I can do this myself! • No framework, where

    do you start? • Rou5ng HTTP requests • Then you need a router • Now to configure the routes • Syntax? Where do I put it? Controllers?
  4. Consistency and flexibility • Frameworks aim to solve many of

    the problems of hand-rolling • Ensures the chosen components work well together • Provide conven=ons that reduce the amount of code a new developer has to understand • If you understanding rou=ng in one Laravel project, it's the same in all of them • The best frameworks not only provide a solid founda=on, but are flexible enough to let you customise
  5. History • Ruby on Rails • Influx of PHP frameworks

    • CodeIgniter • Laravel 1, 2, and 3 • Laravel 4 • Laravel 5
  6. Why Laravel? • Increase developer speed and happiness • Equipping

    and enabling developers • Quick to learn, start, and develop • Write code that's simple, clear, and long-las>ng • Happy developers make the best code
  7. The Laravel community From the very beginning of Laravel, I've

    had this idea that all people want to feel like they are part of something. It's a natural human ins=nct to want to belong and be accepted into a group of other like-minded people. So, by injec=ng personality into a web framework and being really ac=ve with the community, that type of feeling can grow in the community. — Taylor Otwell, Creator of Laravel
  8. Hello, World! // Closure-based route Route::get('/', function () { return

    'Hello, World!'; }); // Controller-based route Route::get('/', 'WelcomeController@index');
  9. Why Laravel? Because Laravel helps you bring your ideas to

    reality with no wasted code, using modern coding standards, supported by a vibrant community, with an empowering ecosystem of tools. And because you, dear developer, deserve to be happy. — Ma% Stauffer, Laravel Up and Runnig
  10. Developing in Laravel • Modern PHP framework requiring PHP >=

    5.6.4 (Laravel 5.4) • Laravel 5.5 will require PHP >= 7.0 • Use what you know - MAMP, WAMP, XAMP • Laravel Valet (Mac) • Laravel Homestead (Vagrant VM)
  11. Crea%ng a new project Using the Laravel installer composer global

    require "laravel/installer" laravel new projectName Using Composer composer create-project laravel/laravel projectName --prefer-dist
  12. Configura)on • The core se*ngs of your Laravel applica6on live

    in files in the config folder • These files simply return an array // config/app.php return [ 'name' => env('APP_NAME', 'My Laravel App'), ];
  13. Tes$ng • Laravel includes PHPUnit out of the box •

    Simplifies tes<ng by providing terse method names for making asser<ons against your code • Dusk provides an easy-to-use browser automa<on and tes<ng API
  14. Rou$ng and Controllers • Core to any web framework is

    taking requests from a user and delivering responses • Usually starts with defining applicaiton routes • Without routes, you have no way to interact with your users
  15. Route defini+ons • Laravel separates web (routes/web.php) and API (routes/

    api.php) routes • Web routes are those visited by your end users • API routes are those consumed by mobile apps, AJAX requests, and more Route::get('/', function () { return 'Hello, World!'; });
  16. Views • Views are files that describe what some par4cular

    output should look like • You can use plain PHP - welcome.php or, • You can use Laravel's Blade templa4ng language - welcome.blade.php • Separates your business logic from your presenta4on logic
  17. Views Route::get('/{name}', function ($name) { return view('welcome')->with('name', $name); }); //

    resources/views/welcome.blade.php <html> <head> <title>Welcome</title> </head> <body> <h1>Hello, {$name}!</h1> </body> </html>
  18. Controllers • Controllers are another part of the MVC pa1ern

    • Organise the logic of one or more routes together in one place • Tend to group similar routes together, par;cularly if your applica;on is structured as a tradi;onal CRUD-applica;on • Controllers will typically handle Create, Read, Update, and Delete opera;ons for a resource php artisan make:controller WelcomeController
  19. Controllers class WelcomeController extends Controller { // The $name variable

    is received from the route parameter, // in the same way as the earlier route closure example. public function index($name) { return view('welcome')->with('name', $name); } }
  20. Ge#ng user input // routes/web.php Route::get('/contact', 'ContactController@create'); // Display the

    contact form Route::post('/contact', 'ContactController@store'); // Save the contact details // app/Http/Controllers/ContactController.php public function store(Request $request) { $contact = new Contact; $contact->name = $request->input('name'); $contact->email = request()->input('email'); $contact->message = request('message'); $contact->save(); return redirect('thank-you'); }
  21. Route model binding A common rou)ng pa-ern is to use

    the first line(s) of a controller to find the resource for the given ID. Route::get('users/{id}', function ($id) { $user = User::findOrFail($id); return view('users.show')->with('user', $user); });
  22. Form method spoofing • Some&mes, yo need to manually define

    HTTP verbs • Javascript • HTML forms only support GET and POST • If you need to use others (PATCH, PUT, DELETE, etc.) you need to specify them yourself • Laravel makes this really easy by spoofing the unsupported methods
  23. Form method spoofing <form action="/users/42" method="POST"> <input type="hidden" name="_method" value="DELETE">

    <!-- or simply --> {{ method_field('DELETE') }} </form> • The hidden _method input tells Laravel that the form you're submi8ng should be treated as something other than a regular POST • Laravel will match and route the submission as if it were actually a request with that verb
  24. CSRF Protec,on • Cross-site request forgery • If you've ever

    tried submi6ng a form already, you have come across a TokenMismatchException • Protects all non-read-only routes (GET, HEAD, or OPTIONS) by default by requiring a token be passed along with each request • Token generated at the start of every seassion • Every non-read-only route compares the submiEed token with the session token
  25. CSRF Protec,on Laravel provides a convenient way of working around

    this <form action="/users/42" method="POST"> <input type="hidden" name="_token" value="{{ csrf_token() }}">" <!-- or simply --> {{ csrf_field() }} <input type="hidden" name="_method" value="DELETE"> </form>
  26. CSRF Projec,on Laravel is configured to support CSRF tokens with

    its suggested JavaScript HTTP client, Axios: <head> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> // resources/assets/js/bootstrap.js let token = document.head.querySelector('meta[name="csrf-token"]'); window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
  27. Templa'ng • Compared to most backend languages, PHP func8ons rela8vely

    well as a templa8ng language • Most modern frameworks include a templa8ng language • Laravel offers a custom engine called Blade, inspired by .NET's Razor engine • Concise syntax, shallow learning curve, powerful and intui8ve inheritance, and easy extensibility
  28. Templa'ng <h1>Users</h1> @forelse ($users as $user) &gt; {{ $user->first_name }}

    {{ $user->last_name }}<br> @empty There are no users at this time @endforelse
  29. Control structures - condi/onals @if • Blade's @if ($condition) compiles

    to <?php if ($condition): ?>. @else, elseif, and @endif also compile to the exact same PHP syntax • Just like na;ve PHP condi;onals, you can mix and match these as necessary
  30. Control structures - condi/onals @unless and @endunless • Unlike @if,

    @unless is new syntax that doesn't have a direct equivalent in PHP • It's the direct inverse of @if • @unless ($condition) == @if (! $condition)
  31. Control structures - loops @for, @foreach, @while Work the same

    way in Blade as they do in PHP @for ($i = 0; $i < 42; $i++ The number is {{ $i }}<br> @endfor @foreach ($users as $user) {{ $user->name }} ({{ $user->email }})<br> @endforeach @while (@item = array_pop($items)) {{ $item->description() }}<br> @endwhile
  32. Control structures - loops @forelse @forelse is a @foreach loop

    that also lets you program in a fallback if the object you're itera7ng over is empty. @forelse ($tasks as $task) &gt; {{ $task->title }}<br> @empty There are no tasks to complete @endforelse
  33. Template inheritance - sec0ons <!-- resources/views/layouts/master.blade.php --> <!DOCTYPE html> <html>

    <head> <title>My Site | @yield('title', 'Home Page')</title> </head> <body> <div class="container"> @yield('content') </div> @section('footerScripts') <script src="app.js"></script> @show </body> </html>
  34. Template inheritance - sec0ons <!-- resources/views/dashboard.blade.php --> @extends('layouts.master') @section('title', 'Dashboard')

    @section('content') Welcome to the application dashboard! @endsection @section('footerScripts') @parent <script src="dashboard.js"></script> @endsection
  35. Template inheritance - sec0ons @include • What if you're in

    a view and you want to display some alert message? • You're surely not going to copy and paste the alert HTML everywhere it's needed <div class="alert alert-success"> The operation was successfully completed </div>
  36. Template inheritance - sec0ons <!-- resources/views/home.blade.php --> <div class="container"> @include('partials.alert',

    [ 'type' => 'success', 'message' => 'The operation was successfully completed', ]) </div> <!-- resources/views/partials/alert.blade.php --> <div class="alert alert-{{ $type }}"> {{ $message }} </div>
  37. Frontend components • Laravel is primarily a PHP framework, but

    also has a series of components focussed on genera=ng frontend code • Components like pagina=on and message bags are PHP helpers that target the frontend • Laravel also provides a webpack-based build system called Mix
  38. Mix • Configura*on layer on top of Webpack • Provides

    a fluent API for defining Webpack build steps for your Laravel applica*on using several common CSS and JavaScript pre-processors • Simple method chaining allows you to fluently define your asset pipeline mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css');
  39. Handling user data • Websites that benefit most from a

    framework o3en don't just serve sta9c content • Many deal with complex and mixed data sources • The most common (and most complex) is user input • Laravel provides tools for gathering, valida9ong, normalising, and filtering user-provided data
  40. Handling user data - request object • Most common tool

    for accessing data • Provides easy access to all of the ways users can provide input • You can also use the global request() helper or the Request facade • Each exposes the same methods, use what you feel most comfortable with
  41. Handling user data - request object $request->all() • As the

    name suggests, gives you an array containing all of the user-provided input
  42. Handling user data - request object $request->except() and $request->only() •

    Provide the same input as $request->all(), but you can choose one or more fields to include or exclude $request->except('_token'); [ 'first_name' => 'Michael', 'last_name' => 'Dyrynda', 'email' => '[email protected]', ] $request->only(['first_name', 'email']); ['first_name' => 'Michael', 'email' => '[email protected]']
  43. Handling user data - request object $request->has() and $request->exists() •

    Detect whether a par,cular piece of user input is available to you • $request->has() returns false if the key exists and is empty • $request->exists() returns true if the key exists, even if it is empty
  44. Handling user data - request object $request->input() • Allows you

    to get the value of a single field • The second parameter allows you to specify a default value, if one was not passed $request->input('first_name', 'Anonymous');
  45. Valida&on • Laravel provides a number of ways to validate

    data • The simplest method is using the validate() method in your controller class PostController extends Controller { public function store(Request $request) { $this->validate($request, [ 'title' => 'required', 'body' => 'required', ]); // Post is valid; persist to database } }
  46. Database and Eloquent • Laravel provides a suite of tools

    for interac3ng with your applica3on's databases • The most notable tool is Eloquent, Laravel's Ac3veRecord ORM implementa3on • Eloquent is one of Laravel's most popular and influen3al features • Simple; one class per table, which is responsible for retrieving, represen3ng, and persis3ng data to that table
  47. Migra&ons • Modern frameworks make it easy to define your

    database structure with code-driven migra:ons • Every new table, column, index, and key can be defined in code • Easy to version, easy share, easy to bring a database up from nothing to default schema in seconds • Migra:ons define two things: the modifica:ons desired when running the migra:on up and when running the migra:on down
  48. Migra&ons <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable

    extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } }
  49. Seeding • Seeding in Laravel is simple • Allows you

    to set your databases up with default data • Useful for specifying default applica<on user groups, roles, and so on • Used to get your applica<on configured in its default state
  50. Seeding - create a seeder php artisan make:seeder ContactsTableSeeder //

    database/seeds/DatabaseSeeder.php public function run() { $this->call(ContactsTableSeeder::class); } // database/seeds/ContactsTableSeeder.php public function run() { DB::table('contacts')->insert([ 'name' => 'Michael Dyrynda', 'email' => '[email protected]', ]); }
  51. Model factories • Model factories define one (or more) pa5erns

    for crea6ng fake entries for your database tables • Par6cularly useful in applica6on tes6ng $factory->define(User::class, function (Faker\Generator $faker) { return [ 'name' => $faker->name, 'email' => $faker->email, ]; }); // Can now be used as factory(User::class)->create();
  52. Query Builder • The query builder lies at the center

    of every piece of Laravel's database func9onality • Fluent interface for interac9ng with your database // Non-fluent $users = DB::select(['table' => 'users', 'where' => ['type' => 'donor']]); // Fluent $users = DB::table('users')->where('type', 'donor')->get();
  53. Eloquent • An Ac&veRecord ORM (Object-rela&onal mapping) • Abstrac&on layer

    that provides a single interface to interact with mul&ple database types • An Eloquent class is responsible for interac&ng with both the table as a whole, and presen&ng individual records • Primarily focussed on simplicity • Like the rest of the framework, relies on conven&on over configura&on
  54. Eloquent - interac/ng with the database // Interacting with the

    table as a whole $users = User::all(); // Interacting with a single record $user = new User; $user->name = 'Jordan'; $user->save();
  55. Eloquent compared to the fluent builder // Retrieving all users

    - builder $users = DB::table('users')->get(); // Retrieving all users - Eloquent $users = User::all(); // Creating a user - builder DB::table('users')->insert([ 'name' => 'Michael', 'email' => '[email protected]' ]); // Creating a user - Eloquent User::create(['name' => 'Michael', 'email' => '[email protected]']);
  56. Laravel Up and Running The best way to learn Laravel

    today. If you’re a capable PHP developer looking to learn Laravel for the first <me, a novice Laravel developer looking to level up, or an experienced Laravel developer looking to learn a few new tricks, this book is for you. It’s clear, concise, and will get you up and running crea<ng powerful and flexible apps in Laravel in no <me. laravelupandrunning.com
  57. Laracasts The most concise screencasts for the working developer, updated

    daily. Laracasts is the defacto educa/onal resource specifically for working developers building the web with PHP and JavaScript. It's kinda like NeBlix for your career! laracasts.com
  58. Thank you • Michael Dyrynda - @michaeldyrynda • North Meets

    South Web Podcast - @northsouthaudio • Laravel News Podcast - @laravelnews