jeudi 27 juillet 2017

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?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire