I am trying to ensure that a record exists in the database before performing a user-related action. When I execute the query directly in my PHPMyAdmin like so (for testing purposes).
SELECT * FROM `chat_participants` WHERE `chat_id` = 2 AND `user_id` = 2
I receive the correct record. However, when I try to use the Laravel Query Builder to achieve the same.
dd($this->participants
->where('chat_id', '=', 2)
->where('user_id', '=', 2)
->get()
->first());
I get null. Is there a way I can ensure that the record exists in the database using Query Builder? Do I need to declare AND in the Query Builder?
Update: I set the participants variable in my constructor.
public function __construct()
{
$this->middleware('auth');
$this->header = DB::table('chat_headers');
$this->participants = DB::table('chat_participants');
$this->messages = DB::table('chat_messages');
}
toSql() produces:
select * from chat_participants`
inner join chat_headers on chat_headers.id = chat_participants.chat_id
inner join chat_rbac on chat_rbac.id = chat_participants.rbac
where chat_participants.chat_id = ? and chat_participants.user_id = ?
and chat_id = ? and user_id = ?
participantsproperty here?$this->participants->where('chat_id', '=', 2)->where('user_id', '=', 2)->toSql()to see what SQL query is being generated. Multiplewhere()calls are automaticallyANDed together. Side note:->get()->first()can just be->first().->get()->first()is redundant btw;->get()will return aCollectionof records that match your query, followed by->first()will return the first of those records. You can simply use->first()to save some calculation time."select * fromchat_participants` inner joinchat_headersonchat_headers.id=chat_participants.chat_idinner joinchat_rbaconchat_rbac.id=chat_participants.rbacwherechat_participants.chat_id= ? andchat_participants.user_id= ? andchat_id= ? anduser_id= ?` @ceejayoz