'bind parameter in whereraw query with join in laravel

below is my code to join two tables and get the latest messages of a particular user_id but i am not able to pass parameter into whereRaw clause. i have tried several ways but no outcome.

$id = $request->user_id;

$chats = DB::table('users')
    ->leftJoin('messages', function($query)
    {
        $query->on('users.id', '=', 'messages.to_id')
        ->whereRaw('messages.id IN (select MAX(messages.id) from messages join users on users.id = messages.to_id where messages.to_id = ? group by users.id)',[$id]);
    })
    ->select('users.id as user_id', 'users.name', DB::raw('CONCAT("https://www.interwebs.co.in/puzzle/attach/", users.avatar) AS image') , 'users.mobile', 'messages.id', 'messages.from_id', 'messages.to_id', 'messages.body as message', 'messages.attachment', 'messages.seen as seen_count', 'messages.created_at')
    ->where('messages.from_id', $request->user_id)
    ->orWhere('messages.to_id', $request->user_id)
    ->get();

it is just showing me the same error every time that undefined variable $id.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source