Today we will use the scopes to show the active users in our web. Although anyone can currently register, later we will add a package of Laravel that allows managing the roles and limit, depending on the role, who can post posts. And we will also format the publishing date of the posts.
Scopes
Scopes are functions that we add to the model that allow us to reuse parts of queries so we do not have to repeat them many times. Open the model User.php and add this code:
1 2 3 |
public function scopeActive($query) { return $query->where('active', 1); } |
And with this, we will be able to easily return active users:
1 2 3 4 5 6 7 8 |
... public function index() { ... $active_users = User::active()->get(); ... return view('posts', ['posts' => $posts, 'active_users' => $active_users]); } ... |
Display them in the view:
1 2 3 4 5 6 |
<h3>Active users</h3> @forelse ($active_users as $user) <p>{{ $user->name }}</p> @empty <p>No users</p> @endforelse |
As you can see, use scopes is very simple and with them we can save writing code, if it is a query that we use several times.
Presenters
Presenters are functions that manipulate the data in the database before displaying it in views. We apply the logic we want (format the date, join two fields, etc.) and then display it in the view.
To create a presenter, I have based on this post.
First, we have to create a Presenters directory in app. And later create a DatePresenter.php file. What our presenter will do is format the creation date:
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App\Presenters; trait DatePresenter { public function getCreatedAtAttribute($value) { return \Carbon\Carbon::parse($value)->format('m/d/Y H:i'); } } |
Add these lines to the Post.php model:
1 2 3 4 5 6 7 8 9 |
use App\Presenters\DatePresenter; ... class Post extends Model { use DatePresenter; ... |
Add to the view this line:
1 |
<p>By {{ $post->user->name }} on {{ $post->created_at }}</p> |
Done this, we would have the date formatted. We can apply it to any other field and put the logic we want.
-
– Presenters: https://murze.be/2016/09/simplifying-presenters-laravel/