如何在laravel 4中为图像名称添加帖子ID号

时间:2014-07-21 22:42:52

标签: php laravel-4 eloquent

我是php新手。我正在用laravel建立一个网站。我想在帖子创建后上传的图片中添加帖子编号,

我的商店控制器:

public function store()
    {
        $validator = Validator::make(Input::all(), Post::$rules);

        if ($validator->passes()) {
            $post = new Post;
            $post->title = Input::get('title');
            $post->body = Input::get('body');
            $post->reporter = Input::get('reporter');
            $post->meta = Input::get('meta');
            $post->slug = Input::get('title');
            $post->top = Input::get('top');
            $post->pubdate = Input::get('pubdate');

            $image = Input::file('image');
            if ($image) {
                $filename = "image274".$image->getClientOriginalExtension();
                Image::make($image->getRealPath())->resize(250, 145)->save('public/images/postimages/'.$filename);
                $post->image = 'images/postimages/'.$filename;
            }


            $categories = Input::get('categories');

            $post->save();

            $post->categories()->sync($categories);

             return Redirect::route('admin.posts.index')
                ->with('message', 'Product Created');
        }

        return Redirect::back()
            ->with('message', 'Something went wrong')
            ->withErrors($validator)
            ->withInput();
    }

有可能吗?请帮帮我。

由于 赛夫

1 个答案:

答案 0 :(得分:0)

您必须先将帖子保存到数据库,然后获取当前保存的帖子ID,然后才能将帖子ID添加到图片文件名中。

以下代码可能会起作用:

public function store()
{
    $validator = Validator::make(Input::all(), Post::$rules);

    if ($validator->passes()) {
        $post = new Post;
        $post->title = Input::get('title');
        $post->body = Input::get('body');
        $post->reporter = Input::get('reporter');
        $post->meta = Input::get('meta');
        $post->slug = Input::get('title');
        $post->top = Input::get('top');
        $post->pubdate = Input::get('pubdate');

        $post->save();

        $image = Input::file('image');
        if ($image) {
            $filename = "image274".$post->id.$image->getClientOriginalExtension();
            Image::make($image->getRealPath())->resize(250, 145)->save('public/images/postimages/'.$filename);
            $post->image = 'images/postimages/'.$filename;
            $post->save();
        }


        $categories = Input::get('categories');

        $post->categories()->sync($categories);

         return Redirect::route('admin.posts.index')
            ->with('message', 'Product Created');
    }

    return Redirect::back()
        ->with('message', 'Something went wrong')
        ->withErrors($validator)
        ->withInput();
}