2014-06-06 89 views
0

我有两列在目录表 1. ID 2.内容Laravel检查id是否存在?

现在这就是我想要做

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存在,我想更新内容列,如果它不是我想创建新的实例,我该怎么做?

+2

使用内容:: firstOrCreate($的数据);它会做同样的 – Saqueib

+0

我相信如果你想更新那条记录你需要传入这个id,否则你无法知道哪一列需要更新,因为内容可能会改变。 – user3158900

回答

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 
+0

未定义的变量,即使我放置$ id之前? – devt204

+0

是的,编辑的版本应该工作,抱歉关于错字,它假设是一个数组。 – har2vey

+0

即使有数组,我仍然得到未定义的变量 – devt204