gileneusz
gileneusz

Reputation: 1485

laravel eloquent - how to select users

I've got two tables:

Users table with id's And Messages table with users's Id as "from" and offer Id's as offer_id

I want to select all users that send messages to with certain offer_id's

For example user with id 1 send few messages:

Id from   offer_id
1. 1,     5
2. 2,     5
3. 1,     5
4. 1,     3

I want to select all users that sent offer_id =5, so users of id 1 and 2

How to do it via eloquent with Message and User class? I've got offer_id given so I can easily select messages:

$messages = Message::where('offer_id', $id);

but how to select users?

edit: I tried this way: in Message model:

public function fromContact()
{
    return $this->hasOne(User::class, 'id', 'from');
}

and then in controller:

$contacts = $messages->fromContact;

but it gives an error

edit migration:

    Schema::create('messages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('from')->unsigned();
        $table->integer('to')->unsigned();
        $table->boolean('read')->default(false);
        $table->integer('offer_id')->nullable();
        $table->mediumText('body')->nullable();
        $table->timestamps();
    });

and error:

"message": "Undefined property: 
Illuminate\\Database\\Eloquent\\Builder::$fromContact",

Upvotes: 1

Views: 4053

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29297

You're missing some closure on your Query Builder. When you use

$messages = Message::where('offer_id', $id);

You don't have an instance of Message until you use a Closure, which are ->first(), ->get(), etc. So using

$message->fromContact;

Will result in an error stating that ->fromContact is not available on a Builder instance. To make this work, use

$messages = Message::where('offer_id', $id)->get();
foreach($messages AS $message){
  $contacts = $message->fromContact;
}

Since this doesn't have much context in a loop, the code above doesn't do anyhting, but $messages->fromContact would also be an error. To get around that, use:

$message = Message::where('offer_id', $id)->first();
$contacts = $message->fromContact;

That should give you a good idea of what's going wrong and how to handle it.

Edit

When looping over multiple Message instances, push $message->fromContact to an array (or Collection) for use later:

$messages = Message::with(['fromContact'])->where('offer_id', $id)->get(); 
// Note: Using `::with()` prevents additional database calls when using `$message->fromContact` in a loop.

$contacts = []; // or $contacts = collect([]);
foreach($messages AS $message){
   $contacts[] = $message->fromContact; // or $contacts->push($message->fromContact);
}

Upvotes: 3

Related Questions