This is the beginning blog post of Laravel relationship series. In this tutorial, we are going to learn how to implement One to One relationship within our Laravel application
Prerequisites
Laravel
To Continue with this tutorial, you should have installed Laravel in your pc. If you are still not installed Laravel in your machine you can configure it from here.
Setting up the Project
First you need to create a new laravel project by running below command in your terminal
public function book() { return $this->hasOne('App\Book'); } }
Book Model
1 2 3 4 5 6 7 8 9 10 11 12
<?php
namespace App; use Illuminate\Database\Eloquent\Model;
class Book extends Model { public function user() { return $this->belongsTo('App\User'); } }
Retrieve Records
1 2 3 4 5
$book = User::find(1)->book; dd($book);
$user = Book::find(1)->user; dd($user);
Create Records
1 2 3 4 5 6
$user = User::find(1); $book = new Book; $book->book = 'Long walk to freedom'; $user->book()->save($book);
Conclusion
In this tutorial, we learnt how to implement One to One relationship within Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.