0

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?

1
  • I think instead of taking input at create function you can just create a new entry as soon as the user clicks creation link, and redirect to /posts/{id}/edit after the creation process. When you pre-create the posts Laravel would insert created_at and updated_at columns by itself, and you can delete unneccessary posts let's say after a day or a week by listing the posts where created_at and updated_at columns are equal. By that you can use ajax calls to upload images by drag and drop using jquery-file-uploader which is pretty easy to implement or just do id dependent things. Commented Jun 20, 2014 at 6:59

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.