jeudi 18 juillet 2019

Laravel - Filter a collection by a dynamic field

The model has 3 fields that are attributes of the model and the 4th field is a dynamic field that is called "fullTitle"

[ { "id": 1, "hours": 2000, "car_id": 3, "fullTitle": "Test", } }

namespace App;

use App\Car;

class VenderModel extends Model { use TranslationTrait;

protected $guarded = ['*'];

/**
 * The accessors to append to the model's array form.
 *
 * @var array
 */
protected $appends = [
    'fullTitle'
];


/**
 * Accessor for dynamic property fullTitle to use as selector name.
 * @param string $locale
 * @return null|string|string[]
 */
public function getFullTitleAttribute($locale = 'es')
{
    if (null === $this->hasTranslation()) {
        return trans('errors.No name');
    }

    return preg_replace('/\s{2,}/', ' ', $this->code.' '. $this->translationOrFirst($locale)->translation);
}

}

public function index(Request $request): JsonResponse
{
    $limit      = $request->input('limit', 25);
    $title      = $request->input('title');

    $query = VenderModel::all();

    $query->when($request->query('title'), function ($q) use ($title) {
        return $q->where('fullTitle', 'like', '%' . $title . '%');
    });

    return response()->json($query, 200);

}

What I'm trying to do is pick up the elements with the fullTitle but doesnt work



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire