If you are not building an API, you can still use Eloquent API Resources to transform your Eloquent models into arrays that can be used in your views. You can create a resource class for your model and define the fields that you want to include in the transformed array. Here's an example:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
In your controller, you can use the resource class to transform your Eloquent models into arrays:
use App\Http\Resources\UserResource;
use App\Models\User;
public function index()
{
$users = User::all();
return view('users.index', [
'users' => UserResource::collection($users),
]);
}
In this example, we're using the UserResource class to transform the User models into arrays that include the id, name, email, created_at, and updated_at fields. We're then passing the transformed arrays to the users.index view.
If you don't want to use a resource class, you can simply call the toArray method on your Eloquent models to get an array representation of the model:
$users = User::all()->map->toArray();
This will give you an array of arrays, where each inner array represents a user and includes all of the model's attributes. However, this approach doesn't give you as much control over the fields that are included in the array, so it's generally better to use a resource class.