How to add relation to default user class in laravel?

Member

by larissa , in category: PHP Frameworks , 6 months ago

How to add relation to default user class in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 6 months ago

@larissa 

To add a relation to the default User class in Laravel, you can define the relation in the User model class.


Here's an example of how you can add a relation to the default User class in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// User.php

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateDatabaseEloquentRelationsHasMany;

class User extends Authenticatable
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}


In this example, we've added a posts method to the User model which defines a hasMany relation to the Post model. This means that a user can have many posts.


You can then access the relation by calling the posts method on a User instance like this:

1
2
$user = User::find(1);
$posts = $user->posts;


This will retrieve all posts associated with the user with the id of 1.


You can define other types of relations (e.g., hasOne, belongsTo, belongsToMany, etc.) in a similar way depending on your application requirements.