php-laravelHow can I create a relationship between two models in Laravel using PHP?
Creating a relationship between two models in Laravel using PHP is done through Eloquent ORM. Eloquent ORM provides a simple ActiveRecord implementation for working with the database. The following example illustrates how to create a relationship between two models in Laravel using PHP:
// Model A
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
// Model B
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
In the example, the User model has a posts method which defines a one-to-many relationship with the Post model. The Post model has a user method which defines a one-to-one relationship with the User model.
The following parts explain the example code:
Usermodel: defines a one-to-many relationship with thePostmodel.postsmethod: defines a one-to-many relationship.Postmodel: defines a one-to-one relationship with theUsermodel.usermethod: defines a one-to-one relationship.
Helpful links
More of Php Laravel
- How can I use the PHP Zipstream library in a Laravel project?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
- How can I use PHP, Laravel, and Vue together to create a web application?
- How can I use PHP and XML to create a Laravel application?
- How can I use PHP Laravel's ZipArchive library to create a zip file?
- How can I use React with PHP Laravel?
- How do I upload a file using PHP and Laravel?
- How can I create a website using the Laravel PHP framework and a template?
- How can I use Laravel Sail to develop a web application with PHP?
- ¿Cómo configurar PHP y Laravel desde cero?
See more codes...