How to create a relationship in laravel?

by wilmer.lemke , in category: PHP Frameworks , a month ago

How to create a relationship in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a month ago

@wilmer.lemke 

To create a relationship in Laravel, you can use Eloquent models and define relationships between them using methods such as belongsTo, hasOne, hasMany, and many more.


Here's an example of how to create a one-to-one relationship between two models:

  1. Create the models:
1
2
php artisan make:model User
php artisan make:model Profile


  1. Define the relationship in the User model:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace App;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}


  1. Define the relationship in the Profile model:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace App;

use IlluminateDatabaseEloquentModel;

class Profile extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}


  1. Use the relationship in your code:
1
2
3
4
5
$user = User::find(1);
$profile = $user->profile;

// Accessing related model's properties
echo $profile->bio;


By defining relationships in your models, you can easily access related data and simplify your database queries in your Laravel application.