Home > Software design >  How to get all Objects of an array with value condition
How to get all Objects of an array with value condition

Time:10-22

I'm absolutely new to php/laravel world so sorry if my question is simple.

Language: php with laravel.

What : I want to get all objects who contain the name of the users.

//Exemple of my users Array
  ($users = ["name1", "name2","name4"])
//Forms is an array who contain multiple object, each object have a reference to a user Name. 
  $Forms = [{_id: 1, title : "title1", userName : "name1" },  {_id: 2, title : "title2", userName : "name2" }, {_id: 3, title : "title3", userName : "name3" }, {_id: 4, title : "title4", userName : "name4" },{_id: 5, title : "title5", userName : "name1" }]

//here i want to get form with name1, name2 and name4 
   foreach ($users  as $user) { 
           $allForm = Forms::where('userName ', $user)->get();  
};

Problematic: I only received 2 objects (objects from the first user of my array).

Exemple: here i want to get every forms who contain "name1", "name2","name4" but i will received only every forms with "name1".

CodePudding user response:

This should work as per your requirements:

$users = ["name1", "name2","name4"];
    $Forms = [
        [
            'id' => 1,
            'title' => 'title1',
            'userName' => 'name1'
        ]
    ];
    $collection = collect($Forms);

    $results = $collection->whereIn('userName', $users)->toArray();

    dd($results);

use toArray() function to convert the collection

CodePudding user response:

Try this

$users = ["name1", "name2","name4"];

$forms = Form::whereIn('userName', $users)->get();


  • Related