skip to Main Content

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".

2

Answers


  1. 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

    Login or Signup to reply.
  2. Try this

    $users = ["name1", "name2","name4"];
    
    $forms = Form::whereIn('userName', $users)->get();
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search