Support the ongoing development of Laravel.io →
Eloquent Blade
Last updated 2 years ago.
0
 /* If 1 package belonging to user */
elseif (count((array)$packageIds) === 1)
{
  $packageId = (array)$packageIds;
  $package = $this->model->find($packageId['0']);
}

This is your problem. With this case, your package is not an array, it's an Eloquent object.

This should fix it:

/* If 1 package belonging to user */
elseif (count((array)$packageIds) === 1)
{
  $packageId = (array)$packageIds;
  $package = array($this->model->find($packageId['0']));
}

And so to the case 0 package id, it should be returns as an array

Last updated 2 years ago.
0

OK, I've just take a closer look at your script. I wonder why you have to do the array casting ? Is this a better way?

/**
 * Get the package/s belonging to a certain user
 * @param int $packageIds
 * @return Object (StdClass)
*/
public function getPackageByUserId(array $packageIds)
{

$packages = array();

/* If no packages belonging to user */
if (count($packageIds) < 1)
{
  $packages[] = $this->createEmptyObject('package', $this->model->table);
}

/* If 1 package belonging to user */
elseif (count($packageIds) === 1)
{
  
  $packages[] = $this->model->find($packageId['0']);
}

/* If more than one package belonging to user */
if (count($packageIds) > 1)
{
  foreach ($packageIds as $packageId)
  {
    $packages[] = $this->model->find($packageId);
  }
}

return $packages; // Is returning array ok ?
}

OH!! Anotherthing, is this script do a Database query ?

$this->model->find($packageId);

If that, in the case with multiple ids, it's a query in a for loop and may harmful to your application's performance. It should do some thing like:

// One query, and you get all the package here, not in the for loop
$this->model->findAllByIds($packageIds); 
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.