I was wondering if you can typehint an array of models in php (more explicitly Laravel).
A code example:
use App\User;
public function index(User $user)
{
// do something with the user
}
My question is, is there a way to typehint an array of User models:
use App\User;
public function index(array User $users) //this is wrong ..
{
// do something with the users
}
In PHP 5.6+ you can use variable length argument lists to achieve what you want.
You unpack the variable as you call the function, and the function uses variadic parameters in its signature. So instead of passing one array of User
objects, you unpack an array
or Collection
of User
objects, and all of them are checked against the typehint you provide.
Example:
function deleteUsers(User ...$users)
{
// delete the users here
}
$users = [$user1, $user2, $user3];
deleteUsers(...$users);
Unpacking will work both on a regular array
and on Laravel Collection
objects, or any other Traversable
variable or literal, to feed into the argument list.
This is the equivalent of doing the following:
deleteUsers($user1, $user2, $user3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With