samuel toh
samuel toh

Reputation: 7076

How can I add brackets on the laravel eloquent? (Laravel 5.3)

My query is like this :

SELECT * FROM message WHERE (seller_id = 1 OR buyer_id = 3) AND deleted_by NOT LIKE '%1%'

I want change it to laravel eloquent

I try like this :

Message::where('seller_id', auth()->user()->id)
       ->orWhere('buyer_id', auth()->user()->id)
       ->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
       ->get();

But, the result like this :

SELECT * FROM message WHERE seller_id = 1 OR buyer_id = 3 AND deleted_by NOT LIKE '%1%'

Seems it need brackets

How can I add brackets on the laravel eloquent?

Upvotes: 10

Views: 7408

Answers (4)

Abdullah Al Shakib
Abdullah Al Shakib

Reputation: 2044

In such cases, use closure.

$userId = auth()->user()->id;
Message::where(function($q) use($userId){
    $q->where('buyer_id', $userId)
    ->orWhere('buyer_id', $userId);
})
->where('deleted_by', 'not like', '%'.$userId.'%')
->get();

Upvotes: 7

Manoj Sharma
Manoj Sharma

Reputation: 1465

Message::where(function ($query) {
    $query->where('seller_id', auth()->user()->id)
      ->orWhere('buyer_id', auth()->user()->id);
})
->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
->get();

Try this, may be your problem get resolved.

Upvotes: 4

EddyTheDove
EddyTheDove

Reputation: 13259

You need to put your where in a closure

Message::where(function($query){
    $query->where('buyer_id', auth()->user()->id)
    ->orWhere('buyer_id', auth()->user()->id);
})
->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')
->get();

Upvotes: 20

Muthu17
Muthu17

Reputation: 1541

Try this :

Message::where(function ($query) {
            $query->where('seller_id', auth()->user()->id)
                  ->orWhere('buyer_id', auth()->user()->id);
        })->where('deleted_by', 'not like', '%'.auth()->user()->id.'%')->get();

Upvotes: 3

Related Questions