M
M
Maxim2019-02-27 11:09:45
Laravel
Maxim, 2019-02-27 11:09:45

How to correctly add record to related tables laravel?

I looked at the manuals, but it’s a bit different from what I need
. I have 2 entities (post and categories) one-to-many relationship
in the code, there may be errors because I write about the method
in the request, an array with category id comes

$post = new Post();
$post->fill($request->validate());
$post->save();

foreach($request->query('categories') as $cat){
 $categories = Categories::find($cat);
$categoris->post_id = $post->id;
$categoies->save();
}

It seems to me that this method is kind of tricky, can you tell me if there is another option to update, (the post and category entities are taken as an example)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Ukolov, 2019-02-27
@alexey-m-ukolov

$post->categories()->sync($request->get('categories'));

L
Lieroes, 2019-02-27
@Lieroes

Documentation

$post = new Post();
$post->create($request->all());

foreach($request->get('categories') as $categoryId){
 $category = Categories::find($categoryId);
 $post->categories()->save($category);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question