Himmators
Himmators

Reputation: 15006

How to check for unique key when saving object to database in laravel?

I'm trying to save to a database, I wish to ignore the post if it's already in the database. This is how I currently save it. The postid has to be unique.

public function save($type, $postid, $url, $author, $content)
{
    $post = new Post;
    $post->type = $type;
    $post->postid = $postid;
    $post->url = $url;
    $post->author = $author;
    $post->content = $content;
    echo $post;

    $post->save();
}

Upvotes: 1

Views: 6732

Answers (3)

You can check unique in validation. I'm not sure if you are checking unique primary postid. I would suggest you to keep postid as primary key & auto increment. You can match the post title for duplication.

$rules = array(
    'postid' => 'required|unique:posts'
);

$validator = Validator::make(Input::all(), $rules);

if($validator->fails()){
    return Redirect::back()->withInput()->with('errors', $validator->messages());
}else{
    $data = array(
        'type' => Input::get('type'),
        'postid' => Input::get('postid'),
        'url' => Input::get('url'),
        'author' => Input::get('author'),
        'content' => Input::get('content')
    );

    if(Post::create($data)){
        Session::flash('messages', 'Post created.');
        return Redirect::route('routename');
    }
}

Upvotes: 0

user1669496
user1669496

Reputation: 33058

Use the Validator class' unique validation rule on whatever fields you wish to be unique before trying to save.

$input = array('postid' => $postid);
$rules = array(
    'postid' => 'unique:posts,postid'
);

$validate = Validator::make($input,$rules);

if($validator->passes())
{
    $this->save($type, $postid, $url, $author, $content)
} 
else 
{
    $messages = $validator->messages();
    echo $messages->first('postid');
}

Upvotes: 6

netvision73
netvision73

Reputation: 4921

You can use Post::findOrFail(UNIQUE_ID) using it in a try ... catch ... structure to fallback if a post has already this unique ID you want to set.

Upvotes: 2

Related Questions