Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // create a liveAware trait
- trait LiveAware
- {
- public function scopeLive(Builder $builder)
- {
- return $builder->whereNotNull('live_at');
- }
- public function isLive()
- {
- return $this->live_at !== null;
- }
- public function isNotLive()
- {
- // the reason we use this way instead of checking $this->live_at === null
- // is if we change the implementation of how to check live. We only need to change code in isLive().
- // So it is more maintable
- return ! $this->isLive();
- }
- }
- // in our controller
- class ArticleController
- {
- public function show(Article $article)
- {
- abort($article->isNotLive(), 404);
- // ...
- }
- }
- // We may wanto use globl scope to tidy things up. But if we create admin pannel, we may want the admin to see the not live
- // articles. We may want to add if check in the global scope. Another way is we can create a middleware for thhis
- class IsLive
- {
- public function handle(Request $request, Closure $next, $model)
- {
- if ($request->{$model}->isNotLive())
- {
- return abort(404);
- }
- return $next($request);
- }
- }
- // In our Cnotroller, we just need to
- class ArticlesController
- {
- public function __construct()
- {
- // register the middleware as is.live in the kernel
- $this->middleware(['is.live:article']);
- }
- public function show(Article $article)
- {
- // ...
- }
- }
Add Comment
Please, Sign In to add comment