0

i have a problem making laravel query:

I want for example:

SELECT * FROM USERS WHERE (a = b) or (b = a)

I have this but is not working:

    $user = Auth::user();
    $id_user = $user->id;
    $message = DB::table('message')
    ->where('sender_id', '=', $user->id)
    ->where('reciver_id', '=', $id)
    ->orWhere(function($query) use ($id,$id_user){
      $query-->where('sender_id', '=', $id)
       ->where('reciver_id', '=', $id_user);
    })
    ->join('users', function ($join) {
       $join->on('users.id', '=', 'message.sender_id')->orWhere('users.id', '=', 'message.reciver_id');
    })->select('users.*', 'message.topic', 'message.message', 'message.read', 'message.created_at as date')
    ->orderBy('date')->get();

    return $message;

2
  • What exactly is not working? Commented Sep 1, 2016 at 20:51
  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please edit these details in or we may not be able to help. Commented Sep 1, 2016 at 21:29

1 Answer 1

1

You should nest the first two wheres in a new one. See the code below:

    $message = DB::table('message')
        ->where(function($query) use ($id,$id_user){
            $query->where('sender_id', '=', $id_user)
                ->where('reciver_id', '=', $id);
        })
        ->orWhere(function($query) use ($id,$id_user){
            $query->where('sender_id', '=', $id)
                ->where('reciver_id', '=', $id_user);
        })
        ->join('users', function ($join) {
            $join->on('users.id', '=', 'message.sender_id')->orWhere('users.id', '=', 'message.reciver_id');
        })->select('users.*', 'message.topic', 'message.message', 'message.read', 'message.created_at as date')
        ->orderBy('date')->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.