Skip to content

Instantly share code, notes, and snippets.

@reinink
Last active November 19, 2018 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reinink/ede56b0c1fde1b0f275dc66fbadab264 to your computer and use it in GitHub Desktop.
Save reinink/ede56b0c1fde1b0f275dc66fbadab264 to your computer and use it in GitHub Desktop.
Add "computed attributes" support to Eloquent models
<?php
namespace App;
use App\Scopes\WithSelects;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable, WithSelects;
protected $casts = [
'last_login_date' => 'datetime',
];
public function selectLastLoginDate()
{
return Login::select('created_at')->whereRaw('user_id = users.id')->latest();
}
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Last Login</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>
@if ($user->last_login_date)
{{ $user->last_login_date->toDayDateTimeString() }}
@else
Never logged in
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
<?php
namespace App\Http\Controllers;
use App\User;
class UsersController extends Controller
{
public function index()
{
return view('users')->withUsers(
User::withSelects('last_login_date')->orderBy('last_name')->get()
);
}
}
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
trait WithSelects
{
public function scopeWithSelect($query, ...$selects)
{
$this->scopeWithSelects($query, ...$selects);
}
public function scopeWithSelects($query, ...$selects)
{
if (is_null($query->getQuery()->columns)) {
$query->select('*');
}
foreach (array_flatten($selects) as $name) {
$subQuery = $this->getModel()->{camel_case('select_'.$name)}();
if ($subQuery instanceof EloquentBuilder) {
$subQuery = $subQuery->getQuery();
}
if ($subQuery instanceof QueryBuilder) {
$subQuery = $subQuery->limit(1);
}
$query->selectSub($subQuery, $name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment