Last active
August 29, 2024 14:39
-
-
Save MrPunyapal/03bb794392ed1789ddb156cbb72872c6 to your computer and use it in GitHub Desktop.
Laravel Eloquent Hack: Automatically Load Relationships and Select Columns π
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 | |
// In Laravel, we have the $with property to automatically load a relationship every time. | |
// However, selecting a specific column by default for every model query doesn't seem possible... | |
// but here's a hack I found! | |
class Post extends Model | |
{ | |
// To automatically load the 'author' relationship on every query | |
protected $with = ['author']; | |
// Boot the model to apply the global scope | |
protected static function boot(): void | |
{ | |
parent::boot(); | |
// Adding a global scope to always include 'user_id' in the select statement | |
static::addGlobalScope('user_id', function (Builder $query): void { | |
// Get the columns that have been selected for the query | |
$columns = $query->getQuery()->columns; | |
// Check if specific columns are being selected and 'user_id' is not among them | |
if ($columns !== null && !in_array('*', $columns) && !in_array('user_id', $columns)) { | |
// Add 'user_id' to the selected columns | |
$query->addSelect('user_id'); | |
} | |
// If no columns are specified, initialize with 'select()' to ensure the scope works | |
if ($columns === null) { | |
$query->select(); | |
} | |
}); | |
} | |
// Define the relationship with 'author' | |
public function author() | |
{ | |
return $this->belongsTo(User::class); | |
} | |
// Other model methods and properties... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment