Laravel - API Resources - Preserving Collection Keys

When returning a resource collection from a route, Laravel resets the collection's keys so that they are in numerical order. However, you may add a preserveKeys property to your resource class indicating whether a collection's original keys should be preserved:


When the preserveKeys property is set to true, collection keys will be preserved when the collection is returned from a route or controller:

    use App\Http\Resources\UserResource;
    use App\Models\User;
    Route::get('/users', function () {
        return UserResource::collection(User::all()->keyBy->id);