Adam
Adam

Reputation: 441

Laravel - Letting users insert categories upon post creation and create new ones if they don't exist

So I'm trying to create the feature for users to add multiple categories when they create a post.

This is an example of a string getting passed to the controller:

$request['categories'] = "Sports, Football, Finals";

This is what I have so far:

TABLES

posts

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


        });

categories

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('name');
        });

category_post

Schema::create('category_post', function(Blueprint $table) {
    $table->integer('category_id')->unsigned();
    $table->integer('post_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
});

Models

Post

class Post extends Model
{
    public function categories()
    {
        return $this->hasMany('App\Category');
    }
}

Category

class Category extends Model
{
    public function post()
    {
        return $this->belongsToMany('App\Post');
    }
}

I don't know if I have set up the tables correctly, if I made the right model relationships and I feel clueless on how to set up the controller.

I got some inspiration from these posts:

  1. How to insert a post with multi category and with multi column deferent category in laravel?
  2. https://laracasts.com/discuss/channels/general-discussion/eloquent-attach-method-for-multiple-inserts-into-a-pivot-table

Upvotes: 0

Views: 1591

Answers (1)

Paras
Paras

Reputation: 9465

Firstly, in many to many Eloquent relationships, you must use the belongsToMany function in both models, so change your Post model like so:

public function categories()
{
    return $this->belongsToMany('App\Category');
}

Also, rename your post function in your Category model to posts and add protected $fillable = ['name']; to your Category model

Finally, for the controller method, you can use the following code:

$categoryStr = $request->input('categories');
$categories = array_map('trim', explode(',', $categoryStr));
foreach ($categories as $category) {
    $catModel = App\Category::firstOrCreate(['name' => $category]);
    $catModel->posts()->save($post); //$post can be the post model that you want to associate with the category
}

Upvotes: 1

Related Questions