Home > Enterprise >  Search Laravel Models for keys containing 'name'
Search Laravel Models for keys containing 'name'

Time:03-30

I'm using Laravel auditing in my project and I need to be able to show the model 'name' field on the view. I get the models like so

        $audit = \OwenIt\Auditing\Models\Audit::find($id);
        $type = $audit->auditable_type;
        $model = $type::where('id',$audit->auditable_id)->get();

and I can loop over the selected model like so

                    foreach ($model[0] as $key => $val) {
                        if (str_contains($key,'name')) {
                            $mname = $key;
                            $mval = $val;
                        }
                    }

the models have various keys identifying the name eg: the User model has 'name', the Organisation model has organisation_name

I want to get the first key and value from each model that contains the string 'name', but using the method above or strpos throws an error saying $mname is not defined. Where am I going wrong?

CodePudding user response:

You can also use first() instead of get(), without having to use $model[0]

  foreach ($model as $key => $val) {
                    if (str_contains($key,'name')) {
                        $mname = $key;
                        $mval = $val;
                    }
                }

CodePudding user response:

So I am not totally sure what you are after however this may work

$models = $type::where('id',$audit->auditable_id)->get();

$modelsWithName = $models->map(function($model) {
    foreach($model->getAttributes() as $attribute) {
        if (str_contains($attribute, 'name')) {
            $model->mname = $attribute;
            return $model;
        }
        return null;
    }
})->filter(function($model) {
    return $model !== null;
});

First we map over your models, we add an attribute called mname to it and set it to the correct attribute, we then return the model, if there is no name attribute we return null, we then filter the nulls out so we end up with a collection of models with mname attribute set.

Also this wont work if you have 2 names .e.g. first_name and last_name

I personally would just add attributes to your models however.. https://laravel.com/docs/9.x/eloquent-mutators

CodePudding user response:

Cracked it by turning it into an array

        $model = $type::where('id', $audit->auditable_id)->first()->toArray();
        foreach ($model as $key => $val) {
            if (str_contains($key, 'name')) {
                $mname = $key;
                $mval = $val;
            }
        }
  • Related