Compare two model objects in Laravel 5.3 or later
If you want to know that if $user === $current_user
then you can compare two model objects in laravel 5.3 or later version with the use of $user->is($current_user)
.
But what if you are using laravel lower than 5.3. We have also covered that to compare two model objects in laravel lower than 5.3.
Read Also: Use sometimes validation with request class – Laravel 7/8
In Laravel 5.2 or earlier.
Before laravel 5.3 we can use the following method to compare two objects.
class User extends Model { public function is(User $user) { return $this->id == $user->id; } }
Here we have used the User model as the parameter of this method. It means the $user
is the instance of User model and will be of the same table. Now we just compare the primary key (assuming it is an id of the table) of both the model objects.
We can improve it a bit more.
class User extends Model { public function is(User $user) { return $this->getKey() == $user->getKey(); } }
The getKey
method will return the primary key of the table and it can be different than the id. Then we can use this method like the example below.
If ( $user->is($current_user) ) { // do your stuff }
But still it has some drawbacks like it can throw an exception if the parameter model is not the User model. Database connection might create the issue.
Model Object Comparison in Laravel 5.3 or later
After this PR, it is added to Laravel 5.3 and now we don’t need to create it ourselves. We can use it directly.
But behind the scene what laravel actually checks to compare two model objects?
Let’s clear about it,
- Database connection should be the same
- Table should be the same
- Primary key of the model should be same (it can be different than id)
You can find it in the vendor at the following path.
Illuminate\Database\Eloquent\Model.php
public function is($model) { return ! is_null($model) && $this->getKey() === $model->getKey() && $this->getTable() === $model->getTable() && $this->getConnectionName() === $model->getConnectionName(); }
And now it is still valid to compare two model objects in Laravel 7.x, 8.x.
If ( $user->is($current_user) ) { // do your stuff }
Hope you find this post useful.
See you in the next learning chapter.