Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data to a pivot table in laravel

I have 3 tables: posts, tags, post_tag.

Each Post has many tags so I use hasMany method for them. But when I choose for example 3 tags in my dropdown list, I can't add them to post_tag and as the result I can't select and show each post's tags.

My Post model:

 class Post extends Eloquent{
 public function tag()
         {
           return  $this->hasMany('Tag');
         }
    }

My Tag model:

class Tag extends Eloquent{
 public function post()
         {
           return  $this->belongsToMany('Post');
         }

}

And my postController:

class postController extends BaseController{

public function addPost(){

    $post=new Post;

    $post_title=Input::get('post_title');
    $post_content=Input::get('post_content');
    $tag_id=Input::get('tag');

    $post->tag()->sync($tag_id);
    $post->save();

I expect to save this post_id save to post_tag table with its tag ids, but it doesn't work. Thanks for your time.

like image 224
saha Avatar asked Jul 03 '14 07:07

saha


People also ask

How do I add values to a pivot table in Laravel?

How can I insert values to pivot table with Laravel best practices? $roles = Input::get('roles'); // arrays of role ids $user = new User(); $user->username = Input::get('username'); $user->password = Hash::make(Input::get('password')); $user->save();

How do I update a pivot table in Laravel?

There are many ways to update the pivot table in Laravel. We can use attach(), detach(), sync(), and pivot attribute to update the intermediate table in Laravel.

How do I save a pivot table in Laravel?

Route::get('/', function () { $user = \App\User::find(2); $job = \App\Job::with('notifications')->find(3); $job->notifications->is_accepted = 'Y'; // is_accepted is pivot table's column $notification = $user->notifications()->save($job); });

How do I create a pivot table in Laravel 8?

You have to run - php artisan make:migration create_project_user_table --create --table=project_user to create the pivot table migration file after that you can copy/paste code in this migration file and run migrate command to create pivot table in your database.


1 Answers

You have a basic idea right, but there are a few issues with your code. Some are stopping it from working and some are just conventional issues.

First off, this is a belongsTomany relationship (you have a pivot table) so you must define both sides of the relationship as belongsToMany (even if hasMany is the way you think about one or both of the side of it). This is because Laravel expects a certain database structure with the two different relationship types.

Another issue (that you found yourself) is that you are adding the tags to the relation (via ->tag()->sync() before you've actually saved the post. You must first save the post (so that laravel knows what ID to add to the pivot table for post_id) and then add the relations. If you are worried about the tags part failing and then having an inconsistent database you should use transactions.

Finally, the 'convention' errors you have is that a belongs-to-many relationship, by definition, involves collections of results. As such, tag and post shoudl be tags and posts respectively.

So here's my rewritten version of your code:

class Post extends Eloquent
{
    public function tags()
    {
        return $this->belongsToMany('Tag');
    }
}

class Tag extends Eloquent
{
    public function posts()
    {
        return $this->belongsToMany('Post');
    }
}

class PostController extends BaseController
{
    public function addPost()
    {
        // assume it won't work
        $success = false;

        DB::beginTransaction();

        try {
            $post = new Post;

            // maybe some validation here...

            $post->title = Input::get('post_title');
            $post->content = Input::get('post_content');

            if ($post->save()) {
                $tag_ids = Input::get('tags');
                $post->tags()->sync($tag_ids);
                $success = true;
            }
        } catch (\Exception $e) {
            // maybe log this exception, but basically it's just here so we can rollback if we get a surprise
        }

        if ($success) {
            DB::commit();
            return Redirect::back()->withSuccessMessage('Post saved');
        } else {
            DB::rollback();
            return Redirect::back()->withErrorMessage('Something went wrong');
        }
    }
}

Now a lot of that controller code centres around the transaction stuff - if you don't care too much about that then you're all good to remove it. Also there are several ways to do that transaction stuff - I've gone with one that's not ideal but gets the point across in a minimal amount of code.

like image 146
alexrussell Avatar answered Sep 18 '22 13:09

alexrussell