Laravel控制器,移动创建和更新到模型?

时间:2017-08-02 08:53:39

标签: laravel laravel-5 eloquent

我的问题是关于如何拆分此代码。我有一个注册表,它的保存功能如下:

public function store(EntityRequestCreate $request)
{
    $geoloc = new Geoloc;
    $geoloc->lat = $request->input('lat');
    $geoloc->lng = $request->input('lng');
    $geoloc->slug = $request->input('name');
    $geoloc->save();

    $user_id = Auth::id();
    $entity = new Entity;
    $entity->name = $request->input('name');
    $entity->type = $request->input('type');
    $entity->email = $request->input('email');
    $entity->tags = $request->input('tags');
    $entity->_geoloc()->associate($geoloc);
    $entity->save();

    $entity_id = $entity->id;

    $address = new Address;
    $address->building_name = $request->input('building_name');
    $address->address = $request->input('address');
    $address->town = $request->input('town');
    $address->postcode = $request->input('postcode');
    $address->telephone = $request->input('telephone');
    $address->entity_id = $entity_id;
    $address->save();

    $role = User::find($user_id);
    $role->role = "2";
    $role->save();

    DB::table('entity_user')->insert(array('entity_id' =>  $entity_id, 'user_id' => $user_id));

    $result = $geoloc->save();
    $result2 = $entity->save();
    $result3 = $address->save();
    $result4 = $role->save();

    if ($result && $result2 && $result3 && $result4) {
        $data = $entity_id;
    }
    else {
        $data = 'error';
    }

    return redirect('profile/entity');
}

如你所见,它有一个自定义请求,它保存到3个模型,这样我的控制器代码太长了(有许多其他功能等)而是我想将此代码移动到模型,作为我的模型到目前为止,它只定义了关系。但是,我并不完全知道如何从控制器调用模型,我是否必须调用它或者它会自动执行?关于如何拆分代码的任何其他想法?

1 个答案:

答案 0 :(得分:0)

您可以使用模型create方法使此代码更短,更易读。

例如:

$geoloc = Geoloc::create(
    $request->only(['lat', 'lng', 'name'])
);

$entity = Entity::create(
    $request->only(['name', 'type', 'email', 'tags])
);
$entity->_geoloc()->associate($geoloc);

$address = Address::create([
    array_merge(
        ['entity_id' => $entity->id],
        $request->only(['building_address', 'address', 'town'])
    )
])

...

create方法将从给定的关联数组创建一个对象。请求对象上的only方法将返回一个关联数组,其中只包含给定键的字段。