I'm trying to extend the User model with another table (Profile) to get the profile picture, location, etc.
Can I override the User model's index()
function to do this?
Current model code:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; protected $fillable = [ 'name', 'email', 'password', 'user_group' ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' => 'datetime', ]; }
What you want to do is create a relationship between the
User
model and the newProfile
model. To do this, you first need to create a modelProfile
and its associated Tabbleprofiles
php artisan make:model Profile --migration
There should be a file named
2022_11_28_223831_create_profiles_table.php
in
database\migrationsNow you need to add a foreign key to indicate which user this profile belongs to.
Now add the following functions in your user model
In your profile model
Run
php artisan migrate
and everything should work as expectedIf you want to test whether the relationship works as expected, create a new test case
php artisan make:test ProfileUserRelationTest
at
tests\Feature\ProfileUserRelationTest.php
Now you can run
php artisan test
to see if everything is fine.CautionThis will refresh your database! So don't test in production.
The output should be like this
Learn more about relationships in Laravel: https://laravel.com/docs/9.x/eloquentrelationships
Learn more about migration: https://laravel.com/docs/9.x/migrations
alternative plan