Jaquarh
Jaquarh

Reputation: 6693

How to Use Laravel Query Builder with and Where Clause in PHP?

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 = ?

Upvotes: 0

Views: 507

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35377

Objects are passed by reference in PHP, this means you're passing a pointer to the same Query Builder object everywhere you use the participants property. So in most cases, you would want to instantiate a new query builder object for each query.

However, PHP does allow for cloning of objects, which would allow you to pass a base query builder and start fresh everywhere you use it:

$query = clone $this->participants;
$query->where(..)->first();

This is an implementation of the Prototype OO pattern, build up a base object and then create a copy of it to do the specifics.

This would be just one way you could avoid hard-coding your table name everywhere you query it.

Upvotes: 2

Related Questions