Reputation: 439
in my web application, people can create posts. Alonng with these posts, they may upload multiple images. To do this, I have a posts table and an image table. Posts hasMany images, and an Image belongs to a post. Therefore, the images table has an image_path column and a post_id column. My trouble is getting the post_id. Because I cant get a post ID before the post has been uploaded, I can't set which post the image belongs to. Anyway, here is some code:
public function create(){
$post = new Post;
$post->title=Input::get('title');
$post->body=Input::get('body');
$post->category=Input::get('category');
$post->save();
$images = Input::file('images');
foreach($images as $image) {
$destinationPath = 'public/uploads/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$id=Auth::id();
$file = new Image();
$file->image_path = 'uploads/' . $image->getClientOriginalName();
$file->description = '';
$file->post_id=Input::get('post_id');
$file->save();
}
What would be the best way to go about fixing this problem?
Upvotes: 0
Views: 335
Reputation: 146229
Once you save the Post
using $post->save()
then you may get the id using:
// ...
$post->save();
/...
$file->post_id = $post->id;
You may try this instead:
// ...
$post->save();
$destinationPath = 'uploads/';
$images = Input::file('images');
foreach($images as $image) {
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
$file = new Image();
$file->image_path = 'uploads/' . $image->getClientOriginalName();
$file->description = '';
$post->images->save($file);
}
Upvotes: 2