Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

class Post extends Eloquent { public static $autoValidate = true; protected static $rules = array(); protected static function boot() { parent::boot(); // You can also replace this with static::creating or static::updating static::saving(function($model) { if ($model::$autoValidate) { return $model->validate(); } }); } public function validate() { } }

Slide 7

Slide 7 text

class Post extends Eloquent { protected static function boot() { parent::boot(); static::updating(function($model) { return false; }); } }

Slide 8

Slide 8 text

class myModel extents Model { public function category() { return $this->belongsTo('myCategoryModel', 'categories_id') ->where('users_id', Auth::user()->id); } }

Slide 9

Slide 9 text

$products = Product::where('category', '=', 3)->get(); $products = Product::where('category', 3)->get(); $products = Product::whereCategory(3)->get();

Slide 10

Slide 10 text

SELECT *, COUNT(*) FROM products GROUP BY category_id HAVING count(*) > 1; DB::table('products') ->select('*', DB::raw('COUNT(*) as products_count')) ->groupBy('category_id') ->having('products_count', '>' , 1) ->get(); Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();

Slide 11

Slide 11 text

$q->whereDate('created_at', date('Y-m-d')); $q->whereDay('created_at', date('d')); $q->whereMonth('created_at', date('m')); $q->whereYear('created_at', date('Y'));

Slide 12

Slide 12 text

// src/Illuminate/Database/Eloquent/Model.php public function save(array $options = array()) // src/Illuminate/Database/Eloquent/Model.php protected function performUpdate(Builder $query, array $options = []) { if ($this->timestamps && array_get($options, 'timestamps', true)) { $this->updateTimestamps(); } $product = Product::find($id); $product->updated_at = '2015-01-01 10:00:00'; $product->save(['timestamps' => false]);

Slide 13

Slide 13 text

// app/Article.php class Article extends Model { use \Dimsav\Translatable\Translatable; public $translatedAttributes = ['name', 'text']; } // database/migrations/create_articles_table.php public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->boolean('online'); $table->timestamps(); }); } // resources/views/article.blade.php

{{ $article->name }}

{{ $article->text }} //database/migrations/create_articles_table.php public function up() { $table->increments('id'); $table->integer('article_id')->unsigned(); $table->string('locale')->index(); $table->string('name'); $table->text('text'); $table->unique(['article_id','locale']); $table->foreign('article_id')->references('id') ->on('articles') ->onDelete('cascade'); } // app/ArticleTranslation.php class ArticleTranslation extends Model { public $timestamps = false; } // app/http/routes.php Route::get('{locale}', function($locale) { app()->setLocale($locale); $article = Article::first(); return view('article')->with(compact('article')); }); http://50LaravelTricksIn50Minutes.com/fr -- French Translation

Slide 14

Slide 14 text

$questions = Question::orderByRaw('RAND()')->take(10)->get();

Slide 15

Slide 15 text

use Ramsey\Uuid\Uuid; trait UUIDModel { public $incrementing = false; protected static function boot() { parent::boot(); static::creating(function ($model) { $key = $model->getKeyName(); if (empty($model->{$key})) { $model->{$key} = (string) $model->generateNewId(); } }); } public function generateNewUuid() { return Uuid::uuid4(); } }

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

class Category extends Model { public function products() { return $this->hasMany('App\Product')->orderBy(‘name'); } }

Slide 18

Slide 18 text

$customer = Customer::find($customer_id); $loyalty_points = $customer->loyalty_points + 50; $customer->update(['loyalty_points' => $loyalty_points]); // adds one loyalty point Customer::find($customer_id)->increment('loyalty_points', 50); // subtracts one loyalty point Customer::find($customer_id)->decrement('loyalty_points', 50);

Slide 19

Slide 19 text

$employees = Employee::where('branch_id', 9)->lists('name', 'id'); return view('customers.create', compact('employees')); {!! Form::select('employee_id', $employees, '') !!} public function getFullNameAttribute() { return $this->name . ' ' . $this->surname; } [2015-07-19 21:47:19] local.ERROR: exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list'' in ...vendor\laravel\framework\src\Illuminate\Database\Connection.php:288 $employees = Employee::where('branch_id', 9)->get()->lists('full_name', 'id');

Slide 20

Slide 20 text

function getFullNameAttribute() { return $this->first_name . ' ' . $this->last_name; } { "id":1, "first_name":"Povilas", "last_name":"Korop", "email":"[email protected]", "created_at":"2015-06-19 08:16:58", "updated_at":"2015-06-19 19:48:09" } class User extends Model { protected $appends = ['full_name']; { "id":1, "first_name":"Povilas", "last_name":"Korop", "email":"[email protected]", "created_at":"2015-06-19 08:16:58", "updated_at":"2015-06-19 19:48:09", "full_name":"Povilas Korop" }

Slide 21

Slide 21 text

class Category extends Model { public function products() { return $this->hasMany('App\Product'); } } public function getIndex() { $categories = Category::with('products')->has('products')->get(); return view('categories.index', compact('categories')); }

Slide 22

Slide 22 text

public function store() { $post = new Post; $post->fill(Input::all()); $post->user_id = Auth::user()->user_id; $post->user; return $post->save() }

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

// eloquent Post::whereSlug('slug')->get(); // instead of View::make('posts.index')->with(‘posts’, $posts); // do this View::make('posts.index')->withPosts($posts);

Slide 25

Slide 25 text

//hide all but the first item @foreach ($menu as $item) @endforeach //apply css to last item only @foreach ($menu as $item)

{{ $item->title }}

@endforeach

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

$devs = [ ['name' => 'Anouar Abdessalam','email' => '[email protected]'], ['name' => 'Bilal Ararou','email' => '[email protected]'] ]; $devs = new Illuminate\Support\Collection($devs); $devs->first(); $devs->last(); $devs->push(['name' => 'xroot','email' => '[email protected]']);

Slide 28

Slide 28 text

$customers = Customer::all(); $us_customers = $customers->filter(function ($customer) { return $customer->country == 'United States'; }); $non_uk_customers = $customers->reject(function ($customer) { return $customer->country == 'United Kingdom'; });

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

// returns a single row as a collection $collection = App\Person::find([1]); // can return multiple rows as a collection $collection = App\Person::find([1, 2, 3]);

Slide 31

Slide 31 text

$collection = App\Person::all(); $programmers = $collection->where('type', 'programmer'); $critic = $collection->where('type', 'critic'); $engineer = $collection->where('type', 'engineer');

Slide 32

Slide 32 text

$collection = App\Person::all(); $names = $collection->implode('first_name', ',');

Slide 33

Slide 33 text

// returns a collection of first names $collection = App\Person::all()->where('type', 'engineer')->lists('first_name'); // returns all the meta records for user 1 $collection = App\WP_Meta::whereUserId(1)->get(); // returns the first & last name meta values $first_name = $collection->where('meta_key', 'first_name')->lists('value')[0]; $last_name = $collection->where('meta_key', 'last_name')->lists('value')[0];

Slide 34

Slide 34 text

class Link extends Model { public function users() { return $this->belongsToMany('Phpleaks\User')->withTimestamps(); } } @if ($link->users->count() > 0) Recently Favorited By @foreach ($link->users()->orderBy('link_user.created_at', 'desc')->take(15)->get() as $user)

{{ $user->name }}

@endforeach @endif

Slide 35

Slide 35 text

$collection = collect([ ['name' => 'Desk'], ['name' => 'Chair'], ['name' => 'Bookcase'] ]); $sorted = $collection->sortBy(function ($product, $key) { return array_search($product['name'], [1=>'Bookcase', 2=>'Desk', 3=>'Chair']); });

Slide 36

Slide 36 text

$library = $books->keyBy('title'); [ 'Lean Startup' => ['title' => 'Lean Startup', 'price' => 10], 'The One Thing' => ['title' => 'The One Thing', 'price' => 15], 'Laravel: Code Bright' => ['title' => 'Laravel: Code Bright', 'price' => 20], 'The 4-Hour Work Week' => ['title' => 'The 4-Hour Work Week', 'price' => 5], ]

Slide 37

Slide 37 text

$collection = App\Person::all(); $grouped = $collection->groupBy('type');

Slide 38

Slide 38 text

// the point is to actually combine results from different models $programmers = \App\Person::where('type', 'programmer')->get(); $critic = \App\Person::where('type', 'critic')->get(); $engineer = \App\Person::where('type', 'engineer')->get(); $collection = new Collection; $all = $collection->merge($programmers)->merge($critic)->merge($engineer);

Slide 39

Slide 39 text

$collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator(); foreach ($collection as $key => $value) { dump($collection->current() . ':' . $collection->getInnerIterator()->current()); }

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

Route::group(['prefix' => 'account', 'as' => 'account.'], function () { Route::get('login', ['as' => 'login', 'uses' => 'AccountController@getLogin']); Route::get('register', ['as' => 'register', 'uses' => 'AccountController@getRegister']); Route::group(['middleware' => 'auth'], function () { Route::get('edit', ['as' => 'edit', 'uses' => 'AccountController@getEdit']); }); }); Login Register Edit Account

Slide 43

Slide 43 text

// app/Http/routes.php Route::group(['middleware' => 'auth'], function () { Route::get('{view}', function ($view) { try { return view($view); } catch (\Exception $e) { abort(404); } })->where('view', '.*'); });

Slide 44

Slide 44 text

// api controller public function show(Car $car) { if (Input::has('fields')) { // do something } } // internal request to api - fields are lost $request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET'); $response = json_decode(Route::dispatch($request)->getContent()); // internal request to api - with fields $originalInput = Request::input(); $request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET'); Request::replace($request->input()); $response = json_decode(Route::dispatch($request)->getContent()); Request::replace($originalInput);

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

// phpunit.xml // .env.test – add to .gitignore TWILIO_ACCOUNT_SID=fillmein TWILIO_ACCOUNT_TOKEN=fillmein // tests/TestCase.php make(Illuminate\Contracts\Console\Kernel::class)->bootstrap(); return $app; } } // access directly from your tests using helper function env('TWILIO_ACCOUNT_TOKEN');

Slide 47

Slide 47 text

// gulpfile.js var elixir = require('laravel-elixir'); mix.phpUnit(); $ gulp tdd

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

// app/Http/Middleware/EncryptCookies.php protected $except = [ 'shared_cookie' ]; Cookie::queue('shared_cookie', 'my_shared_value', 10080, null, '.example.com');

Slide 50

Slide 50 text

$ artisan make:model Books -m

Slide 51

Slide 51 text

$ composer require genealabs/laravel-sparkinstaller --dev // Laravel\Spark\Providers\SparkServiceProvider::class, GeneaLabs\LaravelSparkInstaller\Providers\LaravelSparkInstallerServiceProvider::class, // do not run php artisan spark:install $ php artisan spark:upgrade // backup /resources/views/home.blade.php or it will be overwritten $ php artisan vendor:publish --tag=spark-full

Slide 52

Slide 52 text

createResponse($e); } return response()->view('errors.default', ['exception' => $e], 500); } }

Slide 53

Slide 53 text

// app/Providers/AppServiceProvider.php public function register() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); if ($this->app->environment('production')) { $this->app->register('App\Providers\ProductionErrorHandlerServiceProvider'); } else { $this->app->register('App\Providers\VerboseErrorHandlerServiceProvider'); } }

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

public function up() { Schema::table('users', function($table) { $table->string('name', 50)->change(); }); } $ composer require doctrine/dbal

Slide 56

Slide 56 text

if (view()->exists('emails.' . $template)) { // ... sending an email to the customer }

Slide 57

Slide 57 text

// bootstrap/app.php // replace this: $app = new Illuminate\Foundation\Application( realpath(__DIR__.'/../') ); // with this: $app = new Fantabulous\Application( realpath(__DIR__.'/../') ); basePath.'/FantabulousStorage'; } }

Slide 58

Slide 58 text

class fakeApiCaller { public function getResultsForPath($path) { return [ 'status' => 200, 'body' => json_encode([ 'title' => "Results for path [$path]" ]), 'headers' => [ "Content-Type" => "application/json" ] ]; } } $app->get('{path?}', function($path) { $result = Cache::remember($path, 60, function() use ($path) { return (new fakeApiCaller)->getResultsForPath($path); }); return response($result['body'], $result['status'], array_only( $result['headers'], ['Content-Type', 'X-Pagination'] )); })->where('path', '.*');

Slide 59

Slide 59 text

$ composer create-project laravel/laravel your-project-name-here dev-develop // composer.json { "require": { "php": ">=5.5.9", "laravel/framework": "5.2.*" }, "minimum-stability": "dev" } $ composer update

Slide 60

Slide 60 text

\DB::listen(function($query, $bindings, $time) { var_dump($query); var_dump($bindings); var_dump($time); }); Event::listen('illuminate.query', function($query) { var_dump($query); });

Slide 61

Slide 61 text

// app/Policies/AdminPolicy.php class AdminPolicy { public function managePages($user) { return $user->hasRole(['Administrator', 'Content Editor']); } } // app/Providers/AuthServiceProvider.php public function boot(\Illuminate\Contracts\Auth\Access\GateContract $gate) { foreach (get_class_methods(new \App\Policies\AdminPolicy) as $method) { $gate->define($method, "App\Policies\AdminPolicy@{$method}"); } $this->registerPolicies($gate); } $this->authorize('managePages'); // in Controllers @can('managePages') // in Blade Templates $user->can('managePages'); // via Eloquent

Slide 62

Slide 62 text

$disk= Storage::disk('s3'); $disk->put($targetFile, file_get_contents($sourceFile)); $disk = Storage::disk('s3'); $disk->put($targetFile, fopen($sourceFile, 'r+')); $disk = Storage::disk('s3'); $stream = $disk->getDriver()->readStream($sourceFileOnS3); file_put_contents($targetFile, stream_get_contents($stream), FILE_APPEND); $stream = Storage::disk('s3')->getDriver()->readStream($sourceFile); Storage::disk('sftp')->put($targetFile, $stream)

Slide 63

Slide 63 text

$schedule->call(function () { Storage::delete($logfile); })->weekly();

Slide 64

Slide 64 text

$result = (new Illuminate\Pipeline\Pipeline($container) ->send($something) ->through('ClassOne', 'ClassTwo', 'ClassThree') ->then(function ($something) { return 'foo'; });

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

No content

Slide 68

Slide 68 text

class PurchasePodcastCommand extends Command { public $user; public $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } } class PurchasePodcastCommandHandler { public function handle(BillingGateway $billing) { // Handle the logic to purchase the podcast... event(new PodcastWasPurchased($this->user, $this->podcast)); } } class PodcastController extends Controller { public function purchasePodcastCommand($podcastId) { $this->dispatch( new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) ); } }

Slide 69

Slide 69 text

class PurchasePodcast extends Command implements SelfHandling { protected $user; protected $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } public function handle(BillingGateway $billing) { // Handle the logic to purchase the podcast... event(new PodcastWasPurchased($this->user, $this->podcast)); } } class PodcastController extends Controller { public function purchasePodcast($podcastId) { $this->dispatch( new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId)) ); } }

Slide 70

Slide 70 text

class PodcastController extends Controller { public function purchasePodcast(PurchasePodcastRequest $request) { $this->dispatchFrom('Fantabulous\Commands\PurchasePodcastCommand', $request); } } class PodcastController extends Controller { public function purchasePodcast(PurchasePodcastRequest $request) { $this->dispatchFrom('Fantabulous\Commands\PurchasePodcastCommand', $request, [ 'firstName' => 'Taylor', ]); } }

Slide 71

Slide 71 text

class PurchasePodcast extends Command implements ShouldBeQueued, SerializesModels { public $user; public $podcast; public function __construct(User $user, Podcast $podcast) { $this->user = $user; $this->podcast = $podcast; } }

Slide 72

Slide 72 text

// App\Providers\BusServiceProvider::boot $dispatcher->pipeThrough(['UseDatabaseTransactions', 'LogCommand']); class UseDatabaseTransactions { public function handle($command, $next) { return DB::transaction(function() use ($command, $next) { return $next($command); }); } } // App\Providers\BusServiceProvider::boot $dispatcher->pipeThrough([function($command, $next) { return DB::transaction(function() use ($command, $next) { return $next($command); }); }]);

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

// app/http/routes.php Route::get('/api/posts/{post}', function(Post $post) { return $post; }); // behind the scenes Post::findOrFail($post);

Slide 77

Slide 77 text

$schedule->command('emails:send') ->hourly() ->appendOutputTo($filePath);

Slide 78

Slide 78 text

// returns titles for all posts $titles = $posts->pluck(‘posts.*.title’);

Slide 79

Slide 79 text

$v = Validator::make($request->all(), [ 'person.*.id' => 'exists:users.id', 'person.*.name' => 'required:string', ]);

Slide 80

Slide 80 text

// included in database session driver user_id ip_address

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

No content