@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 2 |
php artisan make:model User php artisan make:model Profile |
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 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 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.