欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel update or create an Item create input:all input:all() Request:all()

 

I have this question about Laravel:

I have a my model and my RestfulAPI controller.

Into the store() method I would check if I have an element that already has the field 'myField' (myField id different from 'id') equal to what I have to create. If it already exist then I would like to update, otherwise I would simply create (save())..

Have I to use find() method?

I have this question about Laravel:

I have a my model and my RestfulAPI controller.

Into the store() method I would check if I have an element that already has the field 'myField' (myField id different from 'id') equal to what I have to create. If it already exist then I would like to update, otherwise I would simply create (save())..

Have I to use find() method?


From my experience, you'll have to traverse table and check for uniqueness. You can create your helper function and use something like array_unique function. Maybe it is worth checking how Validator class is checking that users entry is unique.

shareimprove this answer
 

Currently we have firstOrCreate or firstOrNew, but I don't think they really fit your needs. For instance, firstOrCreate will try to locate a row by all attributes, not just some, so an update in this case wouldn't make sense. So I think you really would have to find it, but you can create a BaseModel and create a createOrUpdate method that could look like this:

This is untested code

class BaseModel extends Eloquent {

    public function createOrUpdate($attributes, $keysToCheck = null)
    {
        // If no attributes are passed, find using all
        $keysToCheck = $keysToCheck ?: $attributes;

        if ($model = static::firstByAttributes(array_only($keysToCheck, $attributes))
        {
            $model->attributes = $attributes;
            $model->save();
        }
        else
        {
            $model = static::create($attributes);
        }

        return $model;
    }

}

This is an implementation of it:

class Post extends BaseModel {

    public function store()
    {
        $model = $this->createOrUpdate(Input::all(), ['full_name']);

        return View::make('post.created', ['model' => $model]);
    }

}
shareimprove this answer
 
 

普通分类: