samedi 7 juillet 2018

Laravel Scope Search a related model

I have a Travel model that references a Country model. I am trying to get list of travel history that has matching country name to the search input via laravel's scopeSearch.

Below is what I've tried so far:

public function scopeSearch($query, $search='')
{
        return $query->orderBy("arrival_date", "desc")
                    ->with(['country' => function ($query) use($search){
                        $query->WhereRaw("name LIKE ? ", '%' . $search . '%');
                    }])
                    ->WhereRaw("destination LIKE ? ", '%' . $search . '%')
                    ->orWhereRaw("city LIKE ? ", '%' . $search . '%')
                    ->whereNull("delete_date");
}

But I am getting empty results. Below is the method that references country model

public function country()
    {
        return $this->belongsTo(Country::class);
    }

Edit: After using toSql()as suggested I'm getting below query

select * from `travel_schedule` where `travel_schedule`.`user_id` = ? and `travel_schedule`.`user_id` is not null and (destination LIKE ?  or city LIKE ?  and `delete_date` is null) order by `arrival_date` desc



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire