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
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.
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,
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.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…