https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
6. 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()
{
}
}
7. class Post extends Eloquent
{
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
return false;
});
}
}
8. class myModel extents Model
{
public function category()
{
return $this->belongsTo('myCategoryModel', 'categories_id')
->where('users_id', Auth::user()->id);
}
}
21. class Category extends Model
{
public function products() {
return $this->hasMany('AppProduct');
}
}
public function getIndex() {
$categories = Category::with('products')->has('products')->get();
return view('categories.index', compact('categories'));
}
22. public function store()
{
$post = new Post;
$post->fill(Input::all());
$post->user_id = Auth::user()->user_id;
$post->user;
return $post->save()
}
25. //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
30. // returns a single row as a collection
$collection = AppPerson::find([1]);
// can return multiple rows as a collection
$collection = AppPerson::find([1, 2, 3]);
33. // returns a collection of first names
$collection = AppPerson::all()->where('type', 'engineer')->lists('first_name');
// returns all the meta records for user 1
$collection = AppWP_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];
34. class Link extends Model
{
public function users()
{
return $this->belongsToMany('PhpleaksUser')->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
38. // the point is to actually combine results from different models
$programmers = AppPerson::where('type', 'programmer')->get();
$critic = AppPerson::where('type', 'critic')->get();
$engineer = AppPerson::where('type', 'engineer')->get();
$collection = new Collection;
$all = $collection->merge($programmers)->merge($critic)->merge($engineer);
51. $ composer require genealabs/laravel-sparkinstaller --dev
//
LaravelSparkProvidersSparkServiceProvider::class,
GeneaLabsLaravelSparkInstallerProvidersLaravelSparkInstallerServiceProvider::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
52. <?php namespace AppExceptions;
use Exception;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use SymfonyComponentDebugExceptionHandler 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);
}
}
53. // app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind(
'IlluminateContractsAuthRegistrar',
'AppServicesRegistrar'
);
if ($this->app->environment('production')) {
$this->app->register('AppProvidersProductionErrorHandlerServiceProvider');
} else {
$this->app->register('AppProvidersVerboseErrorHandlerServiceProvider');
}
}
68. 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))
);
}
}
69. 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))
);
}
}
70. class PodcastController extends Controller
{
public function purchasePodcast(PurchasePodcastRequest $request)
{
$this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request);
}
}
class PodcastController extends Controller
{
public function purchasePodcast(PurchasePodcastRequest $request)
{
$this->dispatchFrom('FantabulousCommandsPurchasePodcastCommand', $request, [
'firstName' => 'Taylor',
]);
}
}
71. class PurchasePodcast extends Command
implements ShouldBeQueued, SerializesModels
{
public $user;
public $podcast;
public function __construct(User $user, Podcast $podcast)
{
$this->user = $user;
$this->podcast = $podcast;
}
}
72. // AppProvidersBusServiceProvider::boot
$dispatcher->pipeThrough(['UseDatabaseTransactions', 'LogCommand']);
class UseDatabaseTransactions
{
public function handle($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}
}
// AppProvidersBusServiceProvider::boot
$dispatcher->pipeThrough([function($command, $next)
{
return DB::transaction(function() use ($command, $next)
{
return $next($command);
});
}]);