I have this code:
$from = $data->chat_from_user; $to = $data->chat_to_user; Log::info($from); // 1 Log::info($to); // 2 $result = DB::connection('mysql_live')->table('user_chatmessages') ->where(function ($query) use ($from, $to) { $query->where('from_user', $from)->where('to_user', $to); })->orWhere(function ($query) { $query->where('from_user', $to)->where('to_user', $from); })->orderBy('date_added', 'asc')->get();
I get an error: Undefined variable: to
.
I have found many topics, but the fix is always to use use()
. But it still tells me the variable is not defined.
For example this works perfectly:
$result = DB::connection('mysql_live')->table('user_chatmessages') ->where(function ($query) { $query->where('from_user', '1')->where('to_user', '2'); })->orWhere(function ($query) { $query->where('from_user', '2')->where('to_user', '1'); })->orderBy('date_added', 'asc')->get();
Advertisement
Answer
There are two closures, you missed at one. Check orWhere
$result = DB::connection('mysql_live')->table('user_chatmessages') ->where(function ($query) use ($from, $to) { $query->where('from_user', $from)->where('to_user', $to); })->orWhere(function ($query) use ($from, $to){ // <- here $query->where('from_user', $to)->where('to_user', $from); })->orderBy('date_added', 'asc')->get();