moyki
moyki

Reputation: 47

Laravel Eloquent creating categories for posts

I have 3 tables posts, categories and post_category. There are 2 categories for example books(1) and magazines(2) for the post. I create the post and choose two categories books and magazines I wanted to save the post_id and also the categories_id in the post_category table how do I insert the two categories in different row and how can i get the id of the post when submitted? btw I tried adding category_id in post table as an array but I'm having a hard time query a single id for the category.

enter image description here

Upvotes: 1

Views: 3632

Answers (3)

sonal
sonal

Reputation: 1

$post = new Post();
$post->title = 'Hello new post';
$post->save();
$category_ids = $input['category_id']; //html name in array 
$post_cat_data = array();
foreach($category_ids as $index => $value) {
    if (!empty($value)) {           
        $post_cat_data[] = [            
        'category_id' => $value,            
       ];
    }       
 }                  
$post->post_category()->createMany($post_cat_data);

Upvotes: 0

thpl
thpl

Reputation: 5910

If you are using Eloquent and you have set the relationships on your models properly, you can use the attach() method on a models relation, to insert new records on the pivot table.

$post = Post::create(['title' => 'Hello Second World']);
$post->categories()->attach([1,2]); // Attaching Category IDs to pivot table
echo $post->id; // Getting the ID

Followup:

The attach() method will only create new records on the pivot table according to the parameters passed, but will not create new instances of the related model

To achieve this you would need to pass the model to the save() method on the relation:

$post = Post::create(['title' => 'Hello World']);
$post->categories()->save(Category::create(['category' => 'Leaflets']));

Thanks to deczo for clarifying this

Upvotes: 0

Anri
Anri

Reputation: 1693

use insert command

$param = array(
        array('post_id' => '1', 'category_id' => 1),
        array('post_id' => '1', 'category_id' => 2),
);

DB::table('post')->insertGetId($param);

NOTE ! it ignores timestamp

LINK HERE

Upvotes: 0

Related Questions