Skip to content

Instantly share code, notes, and snippets.

@reinink
Created July 20, 2017 17:04
Show Gist options
  • Save reinink/d97be9b085ee43e1cecd47df4c81375c to your computer and use it in GitHub Desktop.
Save reinink/d97be9b085ee43e1cecd47df4c81375c to your computer and use it in GitHub Desktop.
Eloquent addSubSelect()
<?php
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
QueryBuilder::macro('addSubSelect', function ($field, $callback) {
$query = $callback();
if (is_null($this->columns)) {
$this->select($this->from.'.*');
}
if ($query instanceof EloquentBuilder) {
$query = $query->getQuery();
}
if ($query instanceof QueryBuilder) {
$query = $query->limit(1);
}
if ($query instanceof Expression) {
$query = $query->getValue();
}
$this->selectSub($query, $field);
});
}
}
<?php
class User extends Model
{
protected $casts = [
'last_login_date' => 'datetime',
];
public function scopeSelectLastLoginDate($query)
{
$query->addSubSelect('last_login_date', function () {
return Login::select('created_at')
->whereRaw('user_id = users.id')
->latest();
});
}
}
<?php
class UsersController extends Controller
{
public function index()
{
return view('users.index')->withUsers(
User::selectLastLoginDate()->orderBy('last_name')->paginate()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment