Eloquent One to Many Relationship CRUD

Update Models with fillable content for Post and a posts method for User.

Post:

    protected $fillable = [
        'title',
        'body',
    ];

User:

    public function posts(){
        return $this->hasMany('App\Models\Post');
    }

Different CRUD statements to add to routes:

Route::get('/create', function () {
    $user = User::findOrFail(1);
    $user->posts()->save($post = new Post(['title'=>'My first post','body'=>'Love Laravel']));
});

Route::get('/read', function () {
    $user = User::findOrFail(1);
    $user->posts()->save($post = new Post(['title'=>'My first post','body'=>'Love Laravel']));
    foreach($user->posts as $post){
        echo $post->title;
    }
});

Route::get('/update', function () {
    $user = User::findOrFail(1);
    $user->posts()->whereId(1)->update(['title'=>'Update to title', 'body'=>'Loving Laravel']);
});

Route::get('/update2', function () {
    $user = User::findOrFail(1);
    $user->posts()->where('id','=',2)->update(['title'=>'Update to title 2', 'body'=>'Loving Laravel']);
});

Route::get('/delete', function () {
    $user = User::findOrFail(1);
    $user->posts()->whereId(1)->delete();
});

//Deletes all with user 1
Route::get('/delete2', function () {
    $user = User::findOrFail(1);
    $user->posts()->delete();
});

Leave a Reply

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