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();
});

Eloquent One to One Relationship CRUD

Different CRUD statements to add to routes:

Route::get('/insert', function () {
    $user = User::findOrFail(1);
    $address = new Address(['name'=>'1234 Houston Ave NY NY 11218']);
    $user->address()->save($address);
});

Route::get('/update', function () {
    $address = Address::whereUserId(1)->first();
    $address->name = '1234 Update Ave Alaska';
    $address->save();
});

Route::get('/read', function () {
    $user = User::findOrFail(1);
    echo $user->address->name;
});

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

Laravel Tinker Updating and deleting

We’ll go into the command line:

php artisan tinker

Now find a record:

$post = App\Models\Post::find(3);

Update like this:

$post->title = "hi"
$post->content = "hi"

In order to save to database write:

$post->save();

To soft delete you just need one line like so:

$post->delete()

To permanently delete this:

$post = App\Models\Post::onlyTrashed()

This will give you an Eloquent Builder response. If you write $post you’ll see it again

Now permanently delete:

$post->forceDelete()

Laravel Tinker Creating Data

We’ll go into the command line to create a new entry in posts:

php artisan tinker

Now add a new record:

$post = App\Models\Post::create(['title'=>'PHP post from tinker','content'=>'PHP content tinker','user_id'=>1]);

It will show you the results of the post including new ID.

To see again type:

$post

This means you can set the variable with all the information before you create a database entry

$post = new App\Models\Post

See the result

$post

Add rest of information:

$post->title = "New title for object"
$post->content = "New content for object"
$post->user_id = 2

See the result

$post

To save this post to the database just do like this:

$post->save()

Eloquent Polymorphic Relation Many to Many

Many to many relationships for polymorphic relations they share a single list of unique records, those unique records are shared amongst the other tables. If we have a post in the Videos table they are going to be sharing tags.

We are going to have a few tables in order to do this:

php artisan make:model Video -m
php artisan make:model Tag -m
php artisan make:model Taggable -m

Open up the video and tag migration to add this:

            $table->string('name');

Open up taggable to add the linking parts. You can remove the increment id and timestamps:

            $table->integer('tag_id');
            $table->integer('taggable_id');
            $table->string('taggable_type');

Now migrate this

php artisan migrate

Now we need to set the relationship starting in the Post model. Write this:

    public function tags() {
        return $this->morphToMany('App\Models\Tag', 'taggable');
    }

Add this exact piece of code to the Video model as well.

On your Tag model we need to define the Post and Video method:

    public function posts() {
        return $this->morphedByMany('App\Models\Post','taggable');
    }
    public function videos() {
        return $this->morphedByMany('App\Models\Video','taggable');
    }

Create two videos and two tags (try javascript and php). Then connect these in your taggables table.

In taggables table you need to choose a tag from the tags table. Then taggable ID refers to the ID from either videos or posts table. Write the taggable_type like this: App\Models\Video. This will put a tag on a post record and a video record.

Let’s pull out a post’s tag:

Route::get('/post/tag', function(){
    $post = Post::find(1);
    foreach($post->tags as $tag){
        echo $tag;
    }
});

Now let’s do the inverse and find the post from the tag. Look inside your taggable table to see you are referencing the correct model (post or video) or else you’ll get back nothing.

use App\Models\Tag;

Route::get('/tag/post', function(){
    $tag = Tag::find(2);
    foreach($tag->posts as $post){
        echo $post->title;
    }
});

Eloquent Polymorphic Relation

Polymorphic relations allow a model to belong to more than one other model in a single association. A really simple example is a users table and a posts table and they both could be related to one other table called photos. So in the photos table we’ll have some columns that would specify the model in which they belong to and the ID of that record. For example, we have one photo record that belongs to the post model with an ID of 1, and this belongs to the user model with an ID of 2.

We are going to have a photos table which will need a new Photo role which we’ll build a migration at the same time:

php artisan make:model Photo -m

Open up the migration and add these to the up function:

            $table->string('path');
            $table->integer('imageable_id');
            $table->string('imageable_type');

Now migrate this

php artisan migrate

Create a few photos in your database. This one is a little more complicated than usual. imageable_id is the ID of the post OR user. imageable_type lets us know which model to reference in this format (App\Models\User).

Now we need to set the relationship starting in the Photo model. Write this:

    public function imageable() {
        return $this->morphTo();
    }

Now we need to set the other tables. Let’s set Post model to pull photos:

    public function photos() {
        return $this->morphMany('App\Models\Photo','imageable');
    }

Add this exact piece of code to the User model as well.

Let’s pull out a user’s photo:

Route::get('/user/photos', function(){
    $user = User::find(1);
    foreach($user->photos as $photo){
        echo $photo;
    }
});

Let’s pull out a post’s photo:

Route::get('/post/photos', function(){
    $post = Post::find(1);
    foreach($post->photos as $photo){
        echo $photo;
    }
});