Wednesday, March 1, 2017

Array_push not working in Laravel

I'm developing a web application in Laravel. The below code is not from the application but gives you a simple idea of the problem I am having.

The following code works

public $my_users = [];  //This is outside function

$users = [];
$users = User::all();
$this->my_users = $users;

That's pretty simple, works fine. However, i want to be able to loop through all of the users and add ones of my choosing like so:

public $my_users = [];  //This is outside function

$users = [];
$all_users = User::all();
foreach ($all_users as $user)
{
    array_push($users, $user);
}
$this->my_users = $users;

Again, what I am doing here has no logic behind it, it's just an example.

In this case both pieces of code should have the same result. However, the second piece of code isn't working. It seems to be the array_push function that isn't working here. is there any reason why this is? What am I to do here?




via Alex Naughton

Advertisement