Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?