Last active
December 29, 2022 18:24
-
-
Save webrobert/83b991bf64c77bef596db6b178898c0b to your computer and use it in GitHub Desktop.
Laravel Dynamic Relationship Or Column
This file contains hidden or 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 | |
// create a dynamic relationship (when there isnt a column to relate to... make one dynamicly!) | |
public function scopeWithLastLogin($query) | |
{ | |
$query->addSelect(['last_login_id' => Login::select('id') | |
->whereColumn('user_id', 'users.id') | |
->latest() | |
->take(1) | |
])->with('lastLogin'); | |
} | |
public function lastLogin() | |
{ | |
return $this->belongsTo(Login::class); | |
} | |
// OR add just a column | |
public function scopeWithProjectName($query) | |
{ | |
$query->addSelect(['project_name' => Project::select('name') | |
->whereColumn('id', 'project_id') | |
->latest() | |
->take(1) | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment