Eloquent One to One Relationship

Update your post migration to have a user_id column

        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });

Update your migrations with

php artisan migrate:refresh

Add a user and a post in your database, where you add the user ID to the new post.

Then update your User model by adding this:

    public function post(){
        return $this->hasOne('App\Model\Post');
    }
The user_id is used as the default connection to Post model. Add a second parameter to use a different id name. Add a third parameter to change the post ID.

Now that we’ve added this relationship, we can display the user’s post in our routes:

use App\Models\User;

/*
|--------------------------------------------------------------------------
| ELOQUENT Relationships
|--------------------------------------------------------------------------
*/

Route::get('/user/{id}/post', function($id){
    return User::find($id)->post->title;
});

Leave a Reply

Your email address will not be published. Required fields are marked *