Created
July 20, 2017 17:04
-
-
Save reinink/d97be9b085ee43e1cecd47df4c81375c to your computer and use it in GitHub Desktop.
Eloquent addSubSelect()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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