2017-08-02 12 views
0

私の質問は、このコードを分割する方法です。他の多くを持つ(見ての通り、それは独自の要求を持っており、それが3つのモデルに保存され、私のコントローラコードその方法はあまりにも長いですLaravelコントローラ、モデルの作成と更新に移動しますか?

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'); 
} 

:私は、登録フォームを持っており、それはこのようになります機能を節約しています関数など)代わりに、このモデルをモデルに移動したいと思います。これまでのモデルで定義された関係のみがあるためです。しかし、コントローラからモデルを呼び出す方法を正確にはわかりません。呼び出す必要がありますか、それとも自動的に行いますか?コードを分割する方法に関する他のアイデア?

答えて

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は、指定されたキーのフィールドのみを持つ関連配列を返します。

+0

モデルをもっと使いたいのですが、現時点では「空間」を使用していないと感じています。関係を定義するだけですが、モデルでそのコードを使用できるのですか? –

関連する問題