Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

t0berius's avatar

laravel strange SQL query builded

I'm using the following model for a message system inside my application:

User model:

public function getMessagesInvolvedAttribute()
{
    return MessageType::where('initiated_by', $this->id)->orWhere('receiver', $this->id)->with(['sender:id,slug'])->orderBy('created_at', 'desc');
}

MessageType model:

public function sender()
{
    return $this->hasOne('App\User', 'id', 'initiated_by');
}

public function receiver()
{
    return $this->hasOne('App\User', 'id', 'receiver');
}

public function messages()
{
    return $this->hasMany('App\Message');
}

public function product()
{
    return $this->hasOne('App\Product', 'id', 'product_id');
}

public function order()
{
    return $this->hasOne('App\Order', 'id', 'order_id');
}

Using the following eloquent query to show some messages of the user

Auth::user()->messages_involved->with(['product', 'order'])->withCount(['messages as unread_messages' => function ($query) {
                $query->where('user_id', '!=', Auth::id())->whereNull('read_on');
            }])->paginate(15),

The following SQL queries are returned (using debugbar):

...some other queries...
select * from `products` where `products`.`id` in ('', 1) and `products`.`deleted_at` is null
select * from `orders` where `orders`.`id` in ('', 1, 2) and `orders`.`deleted_at` is null

I'm a bit confused since '' is included in both queries, any idea why this occurs? Are my relationships fine in general?

0 likes
3 replies
willjohnathan's avatar

Do you have messages_involved records with no product or order id's?

willjohnathan's avatar

Ok, that is why you are getting the ' ' in your IN . It is looking at all messagetypes that belong to that user and they have some with no product ID's / order ID's; so it will use the values of the fields (null) to look up the relation. I don't think that should mess anything up though because you won't have a Null or ' ' id on that table so it won't return anything.

Please or to participate in this conversation.