Miftahul Huda
Miftahul Huda

Reputation: 31

How use conditional relationship in eloquent laravel

I have a 'conversation_message' table and separate sender role by column 'sender_type' (admin/user). Both of admin & user in a different table. But when I call the model, that showed error Call to a member function addEagerConstraints() on null


Table column and data

| id | id_group | id_reply | id_sender | sender_type | message 
| 1  | 1 | null | 3 | admin | Hi, I'm admin
| 2  | 1 | 1 | 3 | admin | I wanna give u promo
| 3  | 1 | 2 | 18 | user | What's promo ?

I've tried if conditional with column value, but it doesn't work.

Conversation_message.php

public function sender(){
        switch($this->sender_type){
            case "user":
                return $this->belongsTo(User::class, 'id_sender', 'id');
            case "admin":
                return $this->belongsTo(Admin::class, 'id_sender', 'id');
            default:
                return;           
        }
    }

InboxController.php

public function message_detail_chat($groupId){
        $data = [];
        $data['messages'] = Conversation_message::with('replies')
                        ->with('sender')
                        ->with('recipients')
                        ->where(['id_group' => $groupId])->get();
}

I expect to use conditional model by column value 'sender_type' but the actual output is wrong.

Upvotes: 3

Views: 2160

Answers (1)

Boni
Boni

Reputation: 348

laravel provide query scope your can read it from here https://laravel.com/docs/5.8/eloquent#local-scopes

   function userSender(){
      $this->belongsTo(User::class, 'id_sender', 'id');
      }

     function adminSender(){

       return $this->belongsTo(Admin::class, 'id_sender', 'id');

     }

public function scopeSender($query)
{
    return $query
          ->when($this->sender_type === 'user',function($q){
              return $q->with('userSender');
         })
         ->when($this->sender_type === 'admin',function($q){
              return $q->with('adminSender');
         }); 

}

Now you can access your Sender like this

     Conversation_message::Sender()->first();

This should give you the right Sender. Hope it helps.

Upvotes: 1

Related Questions