mercredi 2 août 2017

Laravel controller, move creating and updating to model?

my question is about how to split this code. I have a registration form and it's saving function looks like this:

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

As you see, it has a custom request and it is saving to 3 models, that way my controller code is far too long (having many other functions etc) Instead I want to move this code to a model, as my model so far has only relationships defined in it. However I don't exactly know how to call a model from controller, do I have to call it or it will do it automatically? Any other ideas on how to split the code?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire