50 laravel tricks in 50 minutes
TRANSCRIPT
![Page 1: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/1.jpg)
![Page 2: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/2.jpg)
![Page 3: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/3.jpg)
![Page 4: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/4.jpg)
![Page 5: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/5.jpg)
![Page 6: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/6.jpg)
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::updatingstatic::saving(function($model){
if ($model::$autoValidate){
return $model->validate();}
});}
public function validate(){}
}
![Page 7: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/7.jpg)
class Post extends Eloquent{
protected static function boot(){
parent::boot();
static::updating(function($model){
return false;});
}}
![Page 8: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/8.jpg)
class myModel extents Model{
public function category() {
return $this->belongsTo('myCategoryModel', 'categories_id')->where('users_id', Auth::user()->id);
}}
![Page 9: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/9.jpg)
$products = Product::where('category', '=', 3)->get();
$products = Product::where('category', 3)->get();
$products = Product::whereCategory(3)->get();
![Page 10: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/10.jpg)
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();
![Page 11: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/11.jpg)
$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'));
![Page 12: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/12.jpg)
// src/Illuminate/Database/Eloquent/Model.phppublic function save(array $options = array())
// src/Illuminate/Database/Eloquent/Model.phpprotected 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]);
![Page 13: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/13.jpg)
// app/Article.phpclass Article extends Model{
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['name', 'text'];}
// database/migrations/create_articles_table.phppublic function up(){
Schema::create('articles', function (Blueprint $table) {$table->increments('id');$table->boolean('online');$table->timestamps();
});}
// resources/views/article.blade.php<h1>{{ $article->name }}</h1> {{ $article->text }}
//database/migrations/create_articles_table.phppublic 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.phpclass ArticleTranslation extends Model{
public $timestamps = false;}
// app/http/routes.phpRoute::get('{locale}', function($locale) {
app()->setLocale($locale);$article = Article::first();
return view('article')->with(compact('article'));});
http://50LaravelTricksIn50Minutes.com/fr -- French Translation
![Page 14: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/14.jpg)
$questions = Question::orderByRaw('RAND()')->take(10)->get();
![Page 15: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/15.jpg)
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();}
}
![Page 16: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/16.jpg)
![Page 17: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/17.jpg)
class Category extends Model{
public function products(){
return $this->hasMany('App\Product')->orderBy(‘name');}
}
![Page 18: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/18.jpg)
$customer = Customer::find($customer_id);$loyalty_points = $customer->loyalty_points + 50;$customer->update(['loyalty_points' => $loyalty_points]);
// adds one loyalty pointCustomer::find($customer_id)->increment('loyalty_points', 50);
// subtracts one loyalty pointCustomer::find($customer_id)->decrement('loyalty_points', 50);
![Page 19: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/19.jpg)
$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');
![Page 20: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/20.jpg)
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"
}
![Page 21: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/21.jpg)
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'));
}
![Page 22: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/22.jpg)
public function store(){
$post = new Post;$post->fill(Input::all());$post->user_id = Auth::user()->user_id;
$post->user;
return $post->save()}
![Page 23: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/23.jpg)
![Page 24: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/24.jpg)
// eloquentPost::whereSlug('slug')->get();
// instead of View::make('posts.index')->with(‘posts’, $posts);
// do thisView::make('posts.index')->withPosts($posts);
![Page 25: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/25.jpg)
//hide all but the first item@foreach ($menu as $item)<div @if ($item != reset($menu)) class="hidden" @endif><h2>{{ $item->title }}</h2>
</div>@endforeach
//apply css to last item only@foreach ($menu as $item)<div @if ($item == end($menu)) class="no_margin" @endif><h2>{{ $item->title }}</h2>
</div>@endforeach
![Page 26: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/26.jpg)
![Page 27: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/27.jpg)
$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]']);
![Page 28: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/28.jpg)
$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';
});
![Page 29: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/29.jpg)
![Page 30: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/30.jpg)
// 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]);
![Page 31: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/31.jpg)
$collection = App\Person::all();
$programmers = $collection->where('type', 'programmer');$critic = $collection->where('type', 'critic');$engineer = $collection->where('type', 'engineer');
![Page 32: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/32.jpg)
$collection = App\Person::all();
$names = $collection->implode('first_name', ',');
![Page 33: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/33.jpg)
// 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];
![Page 34: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/34.jpg)
class Link extends Model {
public function users(){
return $this->belongsToMany('Phpleaks\User')->withTimestamps();}
}
@if ($link->users->count() > 0)
<strong>Recently Favorited By</strong>
@foreach ($link->users()->orderBy('link_user.created_at', 'desc')->take(15)->get() as $user)
<p><a href="{{ URL::Route('user.show', array('id' => $user->id)) }}">{{ $user->name }}</a>
</p>
@endforeach
@endif
![Page 35: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/35.jpg)
$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']);});
![Page 36: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/36.jpg)
$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],
]
![Page 37: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/37.jpg)
$collection = App\Person::all();
$grouped = $collection->groupBy('type');
![Page 38: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/38.jpg)
// 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);
![Page 39: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/39.jpg)
$collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator();
foreach ($collection as $key => $value) {dump($collection->current() . ':' . $collection->getInnerIterator()->current());
}
![Page 40: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/40.jpg)
![Page 41: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/41.jpg)
![Page 42: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/42.jpg)
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']);
});
});
<a href="{{ route('account.login') }}">Login</a><a href="{{ route('account.register') }}">Register</a><a href="{{ route('account.edit') }}">Edit Account</a>
![Page 43: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/43.jpg)
// app/Http/routes.phpRoute::group(['middleware' => 'auth'], function () {
Route::get('{view}', function ($view) {try {
return view($view);} catch (\Exception $e) {
abort(404);}
})->where('view', '.*');});
![Page 44: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/44.jpg)
// api controllerpublic 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);
![Page 45: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/45.jpg)
![Page 46: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/46.jpg)
// phpunit.xml<php>
<env name="APP_ENV" value="testing"/><env name="CACHE_DRIVER" value="array"/><env name="SESSION_DRIVER" value="array"/><env name="QUEUE_DRIVER" value="sync"/><env name="DB_DATABASE" value=":memory:"/><env name="DB_CONNECTION" value="sqlite"/><env name="TWILIO_FROM_NUMBER" value="+15005550006"/>
</php>
// .env.test – add to .gitignoreTWILIO_ACCOUNT_SID=fillmeinTWILIO_ACCOUNT_TOKEN=fillmein
// tests/TestCase.php<?php
class TestCase extends Illuminate\Foundation\Testing\TestCase{
/*** The base URL to use while testing the application.** @var string*/protected $baseUrl = 'http://localhost';
/*** Creates the application.** @return \Illuminate\Foundation\Application*/public function createApplication(){
$app = require __DIR__.'/../bootstrap/app.php';
if (file_exists(dirname(__DIR__) . '/.env.test')) {Dotenv::load(dirname(__DIR__), '.env.test');
}
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();return $app;
}}
// access directly from your tests using helper functionenv('TWILIO_ACCOUNT_TOKEN');
![Page 47: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/47.jpg)
// gulpfile.jsvar elixir = require('laravel-elixir');
mix.phpUnit();
$ gulp tdd
![Page 48: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/48.jpg)
![Page 49: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/49.jpg)
// app/Http/Middleware/EncryptCookies.phpprotected $except = [
'shared_cookie'];
Cookie::queue('shared_cookie', 'my_shared_value', 10080, null, '.example.com');
![Page 50: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/50.jpg)
$ artisan make:model Books -m
![Page 51: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/51.jpg)
$ 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
![Page 52: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/52.jpg)
<?php namespace App\Exceptions;
use Exception;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;
class Handler extends ExceptionHandler{
protected function convertExceptionToResponse(Exception $e){
$debug = config('app.debug', false);
if ($debug) {return (new SymfonyDisplayer($debug))->createResponse($e);
}
return response()->view('errors.default', ['exception' => $e], 500);}
}
![Page 53: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/53.jpg)
// app/Providers/AppServiceProvider.phppublic 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');
}}
![Page 54: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/54.jpg)
![Page 55: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/55.jpg)
public function up(){
Schema::table('users', function($table){
$table->string('name', 50)->change();});
}
$ composer require doctrine/dbal
![Page 56: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/56.jpg)
if (view()->exists('emails.' . $template)){
// ... sending an email to the customer}
![Page 57: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/57.jpg)
// bootstrap/app.php// replace this:$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../'));
// with this:$app = new Fantabulous\Application(
realpath(__DIR__.'/../'));
<?php namespace Fantabulous;
class Application extends \Illuminate\Foundation\Application{
/*** Get the path to the storage directory.** @return string*/public function storagePath(){
return $this->basePath.'/FantabulousStorage';}
}
![Page 58: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/58.jpg)
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', '.*');
![Page 59: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/59.jpg)
$ 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
![Page 60: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/60.jpg)
\DB::listen(function($query, $bindings, $time) {var_dump($query);var_dump($bindings);var_dump($time);
});
Event::listen('illuminate.query', function($query) {var_dump($query);
});
![Page 61: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/61.jpg)
// app/Policies/AdminPolicy.phpclass AdminPolicy{
public function managePages($user){
return $user->hasRole(['Administrator', 'Content Editor']);}
}
// app/Providers/AuthServiceProvider.phppublic 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
![Page 62: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/62.jpg)
$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)
![Page 63: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/63.jpg)
$schedule->call(function () {Storage::delete($logfile);
})->weekly();
![Page 64: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/64.jpg)
$result = (new Illuminate\Pipeline\Pipeline($container)->send($something)->through('ClassOne', 'ClassTwo', 'ClassThree')->then(function ($something) {
return 'foo';});
![Page 65: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/65.jpg)
![Page 66: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/66.jpg)
![Page 67: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/67.jpg)
![Page 68: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/68.jpg)
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))
);}
}
![Page 69: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/69.jpg)
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))
);}
}
![Page 70: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/70.jpg)
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',
]);}
}
![Page 71: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/71.jpg)
class PurchasePodcast extends Command implements ShouldBeQueued, SerializesModels
{public $user;public $podcast;
public function __construct(User $user, Podcast $podcast){
$this->user = $user;$this->podcast = $podcast;
}}
![Page 72: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/72.jpg)
// 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);});
}]);
![Page 73: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/73.jpg)
![Page 74: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/74.jpg)
![Page 75: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/75.jpg)
![Page 76: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/76.jpg)
// app/http/routes.phpRoute::get('/api/posts/{post}', function(Post $post) {
return $post;});
// behind the scenesPost::findOrFail($post);
![Page 77: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/77.jpg)
$schedule->command('emails:send')->hourly()->appendOutputTo($filePath);
![Page 78: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/78.jpg)
// returns titles for all posts$titles = $posts->pluck(‘posts.*.title’);
![Page 79: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/79.jpg)
<p><input type="text" name="person[1][id]"><input type="text" name="person[1][name]"></p><p><input type="text" name="person[2][id]"><input type="text" name="person[2][name]"></p>
$v = Validator::make($request->all(), ['person.*.id' => 'exists:users.id','person.*.name' => 'required:string',
]);
![Page 80: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/80.jpg)
// included in database session driveruser_idip_address
![Page 81: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/81.jpg)
![Page 82: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/82.jpg)
![Page 83: 50 Laravel Tricks in 50 Minutes](https://reader034.vdocuments.mx/reader034/viewer/2022051318/58ef0e961a28ab42548b4601/html5/thumbnails/83.jpg)