Skip to content

Instantly share code, notes, and snippets.

@webrobert
Last active December 29, 2022 18:24
Show Gist options
  • Save webrobert/83b991bf64c77bef596db6b178898c0b to your computer and use it in GitHub Desktop.
Save webrobert/83b991bf64c77bef596db6b178898c0b to your computer and use it in GitHub Desktop.
Laravel Dynamic Relationship Or Column
<?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