The missing owns() method in Laravel's Eloquent
While Laravel’s Eloquent ORM is pretty powerful and covers all the bases for most of the use cases, there will always be something that is missing. In other words, there will always be a feature that you don’t need until you need it.
For instance, Newton Job has recently shared an owns()
method that he uses in all of his projects. What this method does is pretty simple but pretty handy at the same time.
Let’s look at the method first.
class User extends Authenticatable
{
/**
* Determine if the user owns the given model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $relation
* @return bool
*/
public function owns(Model $model, $relation = 'user'): bool
{
return $model->{$relation}()->is($this);
}
}
As you can tell, the owns()
method takes a model and a relation as arguments. It then checks if the model’s relation is the same as the current user’s. If it is, it returns true; otherwise, it returns false.
Here’s how you can use it.
$user = User::find(1);
$order = Order::find(1);
if ($user->owns($order)) {
// The user owns the order
} else {
// The user does not own the order
}
Or you can specify a different relation.
$user->owns($book, 'author');
You can also use it in a policy like so.
// app/Policies/BookPolicy.php
public function update(User $user, Book $book): bool
{
return $user->owns($book);
}
The cool thing about this method is that it doesn’t query the database. It just compares the IDs of the models and the database connection, which makes it super fast and efficient.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.