John Davidson

php - Search Laravel Models for keys containing 'name'

0 comments
Message:


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?



My Answer:
To search Laravel models for keys containing a specific value, you can use the `where` method along with the `like` operator. Here's an example:

php
$keyword = 'example';

$models = Model::where('key1', 'like', '%' . $keyword . '%')
->orWhere('key2', 'like', '%' . $keyword . '%')
->get();


In this example, `Model` is the name of your Laravel model. Replace `key1` and `key2` with the actual keys you want to search for. The `%` symbols are used as wildcards to match any characters before and after the keyword.

You can add more `orWhere` clauses for additional keys you want to search for. Finally, call the `get` method to retrieve the results.

Rate this post

4 of 5 based on 2251 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us