Search code examples
laravellaravel-5algolialaravel-scout

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?


Solution

  • 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();
      }