Laravel检查id是否存在?

时间:2014-06-06 08:51:38

标签: php laravel laravel-4

我在内容表中有两列  身份证明  2.内容

现在这就是我想要做的事情

Route::post('save', function()
{
    $editor_content=Input::get('editor_content');
    $rules = array('editor_content' => 'required');
    $validator= Validator::make(Input::all(), $rules);
    if($validator->passes())
    {
        //1. check if id is  submitted?
        //2. if id exists update content table 
        //3. else insert new content
            //create new instance
            $content= new Content;
            // insert the content to content column
            $content->content = $editor_content;
            //save the content
            $content->save();
            // check if content has id
            $id=$content->id;

         return Response::json(array('success' => 'sucessfully saved', 'id' => $id));    
        }
    if($validator->fails())
    {
       return $validator->messages() ; 
    }

    });

我想检查ID是否已经提交或检查我是否通过ajax处理请求,如果id存在,我想更新内容列,如果它不想创建新实例如何我这样做吗?

1 个答案:

答案 0 :(得分:0)

替换你的行:

$content= new Content;

使用:

$content = Content::firstOrCreate(array('id' => $editor_content['id'])); //this will check for the id in contents table and create a new record if it doesn't exist