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

Introduction to Laravel - A framework for web a...

Introduction to Laravel - A framework for web artisans

Slides for "Introduction to Laravel PHP Framework" workshop.

Francisco Neves

October 30, 2016
Tweet

More Decks by Francisco Neves

Other Decks in Programming

Transcript

  1. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Model accesses data and contains the business logic of each entity. Example: Get user and check if it is registered or not.
  2. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller View is the visual representation of data. Example: Show details page of a given User ID
  3. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Controller translates requests to actions. Example: PostsController handles requests related to posts
  4. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Controller is the entry point. Request is translated to action.
  5. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller A Controller may call one or many Models to fetch data.
  6. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Model fetches data from database and returns it to Controller.
  7. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Controller passes the fetched data to a given View.
  8. Workshop Laravel - A framework for web artisans Model-View-Controller Model

    View Controller Controller returns the View to the request’s origin.
  9. Workshop Laravel - A framework for web artisans Object-Relational Mapping

    Object’s attributes are mapped to columns of a relational table. class Tweet { private $id; private $text; private $created_at; } PHP Class Relational Table tweets id: integer text: varchar(120) created_at: datetime
  10. Workshop Laravel - A framework for web artisans The Philosophy

    “Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we've attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.” — Taylor Otwell in Laravel.com (2014)
  11. Workshop Laravel - A framework for web artisans The Philosophy

    “Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we've attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.” — Taylor Otwell in Laravel.com (2014)
  12. Workshop Laravel - A framework for web artisans The Philosophy

    “Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we've attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.” — Taylor Otwell in Laravel.com (2014)
  13. Workshop Laravel - A framework for web artisans The Philosophy

    “Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching. Laravel aims to make the development process a pleasing one for the developer without sacrificing application functionality. Happy developers make the best code. To this end, we've attempted to combine the very best of what we have seen in other web frameworks, including frameworks implemented in other languages, such as Ruby on Rails, ASP.NET MVC, and Sinatra. Laravel is accessible, yet powerful, providing powerful tools needed for large, robust applications. A superb inversion of control container, expressive migration system, and tightly integrated unit testing support give you the tools you need to build any application with which you are tasked.” — Taylor Otwell in Laravel.com (2014)
  14. Workshop Laravel - A framework for web artisans The Folder

    Structure Our application workspace: controllers, models, … Bootstrap files like classes auto-loading Application configuration: authentication, database, … Database migrations and seeds Public items, like robots.txt and index.php Views, template’s assets and i18n files Storage folder for sessions, files, etc. Application tests: unit, integration, … Environment parameters Swiss army knife for multiple purposes Project dependencies (PHP packages) Task-manager Project dependencies (Javascript packages) Configuration for testing environment Local server for development only Application’s routes: web, api, ...
  15. Workshop Laravel - A framework for web artisans The Artisan

    CLI Artisan is the name of the command-line interface included with Laravel. It provides helpful commands for your use while developing your application. $ php artisan list # List available commands $ php artisan help migrate # Show help screen for “migrate” $ php artisan migrate --env=testing # Specify configuration environment $ php artisan --version # Show version of Artisan Examples from: http://laravel.com/docs/5.3/artisan
  16. Workshop Laravel - A framework for web artisans The Basic

    Controller $ php artisan make:controller TweetsController app/Http/Controllers/TweetsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TweetsController extends Controller { public function showHello() { return "Hello"; } }
  17. Workshop Laravel - A framework for web artisans The RESTful

    Resource Controller Table from: http://laravel.com/docs/5.3/controllers
  18. Workshop Laravel - A framework for web artisans The RESTful

    Resource Controller $ php artisan make:controller TweetsController --resource app/Http/Controllers/TweetsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TweetsController extends Controller { public function index() {} public function create() { } public function store(Request $request) { } public function show($id) { } public function edit($id) { } public function update(Request $request, $id) { } public function destroy($id) { } }
  19. Workshop Laravel - A framework for web artisans The Router

    component Posts Controller Network Comments Controller Users Controller ?
  20. Workshop Laravel - A framework for web artisans The Router

    component - Foundations http://domain.dev/users/create URL is composed of a protocol, domain and a URI
  21. Workshop Laravel - A framework for web artisans The Router

    component - Foundations A HTTP Request contains a method: GET, POST, HEAD… /users/create HTTP/1.1 domain.com
  22. Workshop Laravel - A framework for web artisans The Router

    component Posts Controller Network Router Comments Controller Users Controller
  23. Workshop Laravel - A framework for web artisans The Router

    component http://domain.dev/users/create UsersController
  24. Workshop Laravel - A framework for web artisans The Router

    component Posts Controller Router Comments Controller Users Controller Request /users will be routed to UsersController
  25. Workshop Laravel - A framework for web artisans The Router

    component Posts Controller Router Comments Controller Users Controller Request /posts/create will be routed to PostsController
  26. Workshop Laravel - A framework for web artisans The Router

    component Posts Controller Router Comments Controller Users Controller Request /comments/1 will be routed to CommentsController
  27. Workshop Laravel - A framework for web artisans The Router

    component Router redirects requests considering the request’s parameters. (It also considers domain)
  28. Workshop Laravel - A framework for web artisans The Basic

    Controller routes/web.php <?php /* * Now, we can access * GET http://domain.com/hello * * "/hello" will be routed to action "showHello" * of TweetsController controller. */ Route::get('/hello', 'TweetsController@showHello'); We must add TweetsController to our web routes table.
  29. Workshop Laravel - A framework for web artisans The RESTful

    Resource Controller routes/web.php <?php /* * Now, we can access * GET http://domain.com/hello * * "/hello" will be routed to action "showHello" * of TweetsController controller. */ Route::resource(’tweets', 'TweetsController'); We must add TweetsController to our web routes table.
  30. Workshop Laravel - A framework for web artisans The Model

    $ php artisan make:model Tweet app/Tweet.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tweet extends Model { // }
  31. Workshop Laravel - A framework for web artisans The Model

    Tweet provides out of the box methods of Eloquent ORM. app/Http/Controllers/TweetsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Tweet; // Import the Tweet model. class TweetsController extends Controller { public function index() { // Return all tweets in database. return Tweet::all(); } } Take a look to other methods: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html
  32. Workshop Laravel - A framework for web artisans The One-One

    Relationship Description from: http://laravel.com/docs/5.3/eloquent#relationships A one-to-one relationship is a very basic relation. A User belongs to one IdentityCard. An IdentityCard belongs to one User. IdentityCards table contains a foreign key column user_id. Users table contains a foreign key column identity_card_id.
  33. Workshop Laravel - A framework for web artisans The One-One

    Relationship We specify that one Tweet belongs to one User app/Tweet.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tweet extends Model { public function user() { return $this->belongsTo(User::class); } }
  34. Workshop Laravel - A framework for web artisans The One-Many

    Relationship Description from: http://laravel.com/docs/5.3/eloquent#relationships A one-to-many relationship is how we say that: A Tweet belongs to one User. A User has many Tweets. Tweets table contains a foreign key column user_id.
  35. Workshop Laravel - A framework for web artisans The One-Many

    Relationship Specify that one User has many Tweets app/User.php <?php namespace App; class User extends Model { public function tweets() { return $this->hasMany(Tweet::class); } }
  36. Workshop Laravel - A framework for web artisans The Many-Many

    Relationship Description from: http://laravel.com/docs/5.3/eloquent#relationships A many-to-many relationship is how we say that: A User has many Jobs (or belongs to many). A Job has many Users (or belongs to many. A pivot table job_user that relates both models must exist with the following foreign keys: job_id, user_id.
  37. Workshop Laravel - A framework for web artisans The Many-Many

    Relationship Specify that one User belongs to many Jobs app/User.php <?php namespace App; class User extends Model { public function jobs() { return $this->belongsToMany(Job::class); } }
  38. Workshop Laravel - A framework for web artisans The Many-Many

    Relationship Specify that one Job belongs to many Users app/Job.php <?php namespace App; class Job extends Model { public function users() { return $this->belongsToMany(User::class); } }
  39. Workshop Laravel - A framework for web artisans The Blade

    Templating Description from: http://laravel.com/docs/5.3/templates#blade-templating Blade is a powerful templating engine provided with Laravel. Blade is driven by template inheritance and sections. All Blade files should end with the .blade.php extension.
  40. Workshop Laravel - A framework for web artisans The View

    with Blade Templating With Blade Templating, create a master layout. resources/views/layouts/master.blade.php <html> <head> ... </head> <body> @section('header') This is the header. @stop <div class="container"> @yield('content') </div> </body> </html>
  41. Workshop Laravel - A framework for web artisans The View

    with Blade Templating Controller passes data to view resources/views/tweets/index.blade.php app/Http/Controllers/TweetsController.php <?php ... use App\Tweet; class TweetsController extends Controller { public function index() { $tweets = Tweet::all(); // Pass data to view "tweets/index.blade.php" and return return view('tweets.index', ['tweets' => $tweets]); } } More about passing data to views: https://laravel.com/docs/5.3/views
  42. Workshop Laravel - A framework for web artisans The View

    with Blade Templating View extends sections of master layout and override content resources/views/tweets/index.blade.php @extends('layouts.master') @section('header') <p>This is appended to the master header.</p> @endsection @section('content') <p>This is my body content, where will be shown my tweets.</p> @foreach ($tweets as $tweet) <p>This is tweet "{{ $tweet->id }}"</p> @endforeach @endsection Take a look to other Blade Templating features: https://laravel.com/docs/5.3/blade
  43. Workshop Laravel - A framework for web artisans The Database

    Migrations Note: We need to create a database before calling migrations. Description from: http://laravel.com/docs/5.3/migrations Migrations are a type of version control for your database. Allow to modify the database schema. Migrations are typically paired with the Schema Builder.
  44. Workshop Laravel - A framework for web artisans The Schema

    Builder More about Schema Builder: http://laravel.com/docs/5.3/schema Provides a database agnostic way of manipulating tables. All of the databases supported by Laravel, with an unified API.
  45. Workshop Laravel - A framework for web artisans The Database

    Migration $ php artisan make:migration create_tweets_table database/migrations/xxx_create_tweets_table.php class CreateTweetsTable extends Migration { public function up() { Schema::create('tweets', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); // Owner of tweet $table->string('text'); $table->foreign('user_id')->references('id')->on('users'); }); } public function down() { Schema::drop('tweets'); } }
  46. Workshop Laravel - A framework for web artisans The Database

    Migration Migrations can be rolled back, too. It’s like a version control for your database. Reset everything is possible, too. $ php artisan migrate:install # Create “migrations” table $ php artisan migrate # Migrate a database to next version $ php artisan migrate:rollback # Rollback database version $ php artisan migrate:status # Show current status of database Examples from: Artisan CLI
  47. Workshop Laravel - A framework for web artisans The Database

    Seeder Description from: http://laravel.com/docs/5.3/migrations#database-seeding Laravel also includes a simple way to seed your database. All seed classes are stored in database/seeds. They are useful for testing or first time deployment, i.e, to create administrator accounts. Use DatabaseSeeder class, to run other seed classes.
  48. Workshop Laravel - A framework for web artisans The Database

    Seed Create a Seeder class for each persisted entity. database/seeds/UsersTableSeeder.php <?php use Illuminate\Database\Seeder; use App\User; class UsersTableSeeder extends Seeder { public function run() { User::create([ 'name' => 'First User', 'email' => '[email protected]', 'org' => 'Hackathonners', ]); } }
  49. Workshop Laravel - A framework for web artisans The Database

    Seed Update DatabaseSeeder. You can choose the order of seeding. database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(UsersTableSeeder::class); } }
  50. Workshop Laravel - A framework for web artisans The Database

    Seed Database may be seeded or reset Use seeders when you’re testing you app or need administrators in application deployment. $ php artisan db:seed # Seed database Examples from: Artisan CLI
  51. Workshop Laravel - A framework for web artisans Validating Form

    Requests $ php artisan make:request CreateTweetRequest app/Requests/CreateTweetRequest.php <?php namespace App\Http\Requests\Registration; use App\Http\Requests\Request; class CreateTweetRequest extends Request { public function authorize() { return true; } public function rules() { return [ 'text' => 'required|min:1|max:120' ]; } }
  52. Workshop Laravel - A framework for web artisans Validating Form

    Requests When method is called, then validation succeeded app/Controllers/TweetsController.php <?php namespace App\Http\Controllers; use App\Requests\CreateTweetRequest; use App\Tweet; class TweetsController extends Controller { public function store(CreateTweetRequest $request) { // Laravel injects the dependency (object) in this method // Form is valid when this method is called // Save tweet to database. Tweet::create([ 'text' => $request->input('text') ]); } }
  53. Workshop Laravel - A framework for web artisans The Community

    Laravel Official Website http://laravel.com Laravel IO Forum http://laravel.io Laravel Screencasts http://laracasts.com Laravel Podcasts http://podbay.fm/show/653204183