athulpraj's avatar

how to skip one element from collection

I want to skip the first element from a collection what should i add to my current code .. which is :

$games = $user->getProjects()->sortByDesc('created_at');
0 likes
9 replies
veve286's avatar

$games = $user->getProjects()->sortByDesc('created_at')->forget(0);

1 like
lara33495's avatar
Level 1

just try i hope it will work :P

$games = $user->getProjects()->sortByDesc('created_at');
$game = $games->slice(1,count($games));
1 like
lara33495's avatar

if you get error somehow find number of collection and use slice you can simply play with Laravel :)

athulpraj's avatar
$games = $user->getProjects()->sortByDesc('created_at')->shift();

nop shift also din work .. is there any chance that the collection is not defined properly .. coz i am getting this with eloquent and i dont need the first item .. i need rest of the items ..

tykus's avatar

shift() removes the first item and returns it, so what you have done it assign games to the first item in the collection; whereas the collection contains all of the other elements:

$games = $user->getProjects()->sortByDesc('created_at'); // all of the games
$games->shift();  // removes the first game and returns it
$games->all(); // remaining games

You could also use slice() (per @Hamelraj) or splice() if you wanted to inline it:

$games = $user->getProjects()->sortByDesc('created_at')->splice(1);
1 like
ohffs's avatar

I think you could use take() and skip() too? Eg,

$games = User::projects()->skip(1)->take(1000)->get();
1 like

Please or to participate in this conversation.