Introduction to Laravel Framework (5.2)

Preview:

Citation preview

THE PHP FRAMEWORK FOR WEB ARTISANS

1

By Viral SolaniTech Lead

Cygnet Infotech

Why Laravel ? Good Question !

• Inspired from battle tested frameworks (ROR , .Net)• Built on top of symfony2 components• Guides new developers to use good practices.• Easy Learning Curve.• Survived the PHP Framework War , now its one of the most used frameworks.• Expressive Syntax • Utilizes the latest PHP features (Namespaces , Interface , PSR-4

Auto loading , Ioc )

•Active and growing community that can provide quick support and answers

•Out of box Authentication , Localization etc.

• Well Documented (http://laravel.com/docs)2

Modern Framework

• Routing

• Controllers

• Template Systems (Blade)

• Validation

• ORM (Eloquent)

• Authentication out of the box

• Logging

• Events

• Mail

➢ Queues ➢ Task Scheduling➢ Elixier➢ Localization➢ Unit Testing (PHPunit)➢ The list goes on….

3

What is Composer ?

•Composer is a tool for Dependency Management for PHP.

•Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

4

Your Awesome

PHPProject

(1) Read composer.json

(2) Find Library form Packagist

(3) Download Library(4) Library downloadedon your project

How Composer works?

5

How to install Laravel ??

You can install Laravel by Three ways

- via laravel installer

- via composer

- clone from github

6

This will download laravel installer via composer-composer global require "laravel/installer"

When installer added this simple command will create app-laravel new <app name>

* Do not forget to add ~/.composer/vendor/bin to your PATH variable in ~/.bashrc

Via Laravel Installer

7

Via composer

- composer create-project laravel/laravel your-project-name

Get from GitHub-https://github.com/laravel/laravel-And then in the project dir run “composer install” to get all needed packages

Other Options

8

Laravel Directory Structure

App

Bootstrap

Config

Database

Public

Resources

Storage

Tests

Vendor

.env

.env.example

.gitattribuites

.gitignore

Artisan

Composer.lock

Composer.json

Gulpfile.js

Package.json

Phpunit.xml

Readme.md

Server.php

9

Laravel Directory Structure : App

10

Routes

• Create routes at: app/Http/routes.php• include() additional route definitions if needed• Below Methods are available.

– Route::get();– Route::post();– Route::put();– Route::patch();– Route::delete();– Route::any(); //all of above

11

Routes

app/Http/routes.php

Route::get('/', function(){ echo ‘Boom!’;

});

12

Routes

13

Controllers

Command : php artisan make:controller PhotoController

• The Artisan command will generate a controller file at app/Http/Controllers/PhotoController.php.

• The controller will contain a method for each of the available resource operations.

14

Resource Controller

php artisan make:controller PhotoController --resource

Route::resource('photos', 'PhotoController');

15

Views

• Views contain the HTML served by your application and separate your controller / application logic from your presentation logic.

• Views are stored in the resources/views directory.

• Can be separated in subdirectories• Can be both blade or simple php files

16

Blade Template Engine

• Laravel default template engine

• Files need to use .blade.php extension

• Driven by inheritance and sections

• all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

• Extensible for adding new custom control structures (directives)

17

Defining a Layout

<!-- Stored in resources/views/layouts/app.blade.php --><html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show

<div class="container"> @yield('content') </div> </body></html>

18

Extending a Layout

<!-- Stored in resources/views/child.blade.php -->

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar') @parent

<p>This is appended to the master sidebar.</p>@endsection

@section('content') <p>This is my body content.</p>@endsection

19

View System

• Returning a view from a route

Route::get('/', function(){

return view('home.index');//resources/views/home/index.blade.php

});

• Sending data to view

Route::get('/', function(){

return view(‘home.index')->with('email', 'email@gmail.com');});

20

Models

• Command to create model : php artisan make:model User

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{ /** * The table associated with the model. * * @var string */ protected $table = 'tablename';}

21

Eloquent ORM

• Active Record

• Table – plural, snake_case class name• Has a lot of useful methods• is very flexible• Has built in safe delete functionality• Has built in Relationship functionality

• Timestamps• Has option to define scopes

22

Eloquent ORM - Examples

$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10) ->get();

// Retrieve a model by its primary key...$flight = App\Flight::find(1);

// Retrieve the first model matching the query constraints...$flight = App\Flight::where('active', 1)->first();

$flights = App\Flight::find([1, 2, 3]);

//Retrieving Aggregates

$count = App\Flight::where('active', 1)->count();$max = App\Flight::where('active', 1)->max('price');

23

Query Builder

• The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.

• Simple and Easy to Understand• Used extensively by Eloquent ORM

24

Query Builder - Examples

//Retrieving All Rows From A Table

$users = DB::table('users')->get();

//Retrieving A Single Row / Column From A Table

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name;

//Joins

$users = DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get();

25

Migrations & Seeders

• “Versioning” for your database , and fake data generator

• php artisan make:migration create_users_table

• php artisan make:migration add_votes_to_users_table

• php artisan make:seeder UsersTableSeeder

• php artisan db:seed

• php artisan db:seed --class=UsersTableSeeder

• php artisan migrate:refresh --seed26

Examples of Migration & Seeding

27

Middleware

• Route Filters

• Allows processing or filtering of requests entering the system

• Better , Faster , Stronger

• Defining Middleware : php artisan make:middleware Authenticate

• If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

28

Middleware : Example

29

Middleware - Popular Uses :

• Auth

• ACL

• Session

• Caching

• Debug

• Logging

• Analytics

• Rate Limiting

30

Requests

• Command to Create Request php artisan make:request StoreBlogPostRequest

• Validators That are executed before hitting the action of the Controller

• Basically Designed for Authorization and Form validation

31

Requests : Example

32

Service Providers

• Command to create Service Provider : php artisan make:provider

• Located at : app/Providers

• Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.

• But, what do we mean by "bootstrapped"? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

33

Service Container

• The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.

• Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

• You need to bind all your service containers , it will be most probably registered within service providers.

34

Service Container : Example

35

Facades

• Facade::doSomethingCool()

• Isn’t that a static method? - Well, no

• A «static» access to underlying service

• Look like static resources, but actually uses services underneath

• Classes are resolved behind the scene via Service Containers• Laravel has a lot usefull usages of Facades like

– App::config()– View::make()– DB::table()– Mail::send()– Request::get()– Session::get()– Url::route()– And much more…

36

Encryption

• Simplified encryption using OpenSSL and the AES-256-CBC cipher

• Available as Facade Crypt::encrypt() &Crypt::decrypt()

• Before using Laravel's encrypter, you should set the key option of your config/app.phpconfiguration file to a 32 character, random string. If this value is not properly set, all values encrypted by Laravel will be insecure.

37

Artisan (CLI)

• Generates Skeleton Classes • It runs migration and seeders• It catches a lot of stuff (speed things up)• It execute custom commands • Command : Php artisan

38

Ecosystem

• Laravel

• Lumen

• Socialite

• Cashier

• Elixir

• Envoyer

• Spark

• Homestead

• Valet

• Forge

39

Lumen

• Micor-framework for Micro-services

• Sacrifices configurability for speed

• Easy upgrade to a full Laravel application

40

Socialite

• Integrates Social authentication functionality

• Almost for all popular platforms available

• http://socialiteproviders.github.io

41

Cashier

• Billing without the hassle

• Subscription logic included

• Easy to setup

42

Elixir

• Gulp simplified

• Compilation, concatenation, minifaction, auto-prefixing,…

• Support for

– Source Maps

– CoffeScript

– Browserify

– Babel

– …

43

Spark

• Billing

• Team management

• Invitations

• Registration

• 2-factor auth

• …

44

Homestead

• Comes with everything you need– Ubuntu

– PHP 5.6 & 7

– Nginx

– MySQL & Postgres

– Node

– Memcached

– Redis

– ---

45

Forge

• Automates the process to setup a server

• You don’t need to learn how to set up one

• Saves you the effort of settings everything up

• Globally, saves you ridiculous amounts of time

46

Envoyer (!= Envoy)

• Zero downtime deployments

• Seamless rollbacks

• Cronjobs monitoring with heartbeats

• Deployment health status

• Deploy on multiple servers at once

47

Community

• Slack http://larachat.co/

• Forum https://laracasts.com/discuss• Forum http://laravel.io/forum

• Twitter https://twitter.com/laravelphp• GitHub https://github.com/laravel/laravel

48

Conference

• LaraconUS July 27-29, Kentucky USAhttp://laracon.us/

• LaraconEU August 23-24, Amsterdam NL http://laracon.eu

49

Learning

• Laravel Documentation https://laravel.com/

• Laracastshttps://laracasts.com/

50

CMS

• AsgardCMS https://asgardcms.com/

• OctoberCMS http://octobercms.com/

• Laravel 5 Boilerplate

https://github.com/rappasoft/laravel-5-boilerplate

51

52

Recommended