Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typehinting array of models

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
}
like image 227
RVandersteen Avatar asked Dec 19 '22 01:12

RVandersteen


1 Answers

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);
like image 61
Torkil Johnsen Avatar answered Jan 31 '23 02:01

Torkil Johnsen