Przemek Wojtas
Przemek Wojtas

Reputation: 1371

Laravel scout check if relation is not empty?

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Event extends Model
{
    protected $table = 'events';
    public $timestamps = true;

    use Searchable;
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    public function entities()
    {
        return $this->belongsTo('App\Entity', 'entity_id');
    }
    public function users()
    {
        return $this->belongsTo('App\User', 'id');
    }
    public function events()
    {
        return $this->belongsTo('App\DirtyEvent', 'id');
    }
    public function toSearchableArray()
    {
        $data = $this->toArray();
        $data['entities'] = $this->entities->toArray();
        return $data;
    }
}

This is my model for Event, as you can see I am using toSearchableArray which is Laravel scout function to import 'relations' to algolia. However the problem is that sometimes it is empty. So for example

event id 1 has entity_id 1

but in another example

event id 2 has entity_id = null

How can I modify this function to check if the entities() relation is not empty before putting it into array?

Upvotes: 0

Views: 1147

Answers (3)

sabonzy
sabonzy

Reputation: 26

if i understand u correctly this should help. if the relationship does not exist return an empty array and scout won't update the index

  public function toSearchableArray()
    {

      if(is_null($this->entities)){
        return [];
         }

       $this->entities

     return $this->toArray();
  }

Upvotes: 1

Julien Bourdeau
Julien Bourdeau

Reputation: 1193

I think if load the relation before the toArray().

public function toSearchableArray()
{
    $this->entities;

    return $this->toArray();
}

Upvotes: 0

mohamed ali
mohamed ali

Reputation: 91

please update foreign_key in relation as this
user_id as foreign_key instead of id
event_id as foreign_key instead of id

public function users()
{
    return $this->belongsTo('App\User', 'user_id');
}
public function events()
{
    return $this->belongsTo('App\DirtyEvent', 'event_id');
}

Upvotes: 0

Related Questions