antweny
antweny

Reputation: 87

How to pass multiple values from controller to view

I have a form which has many dropdowns which a populated from different tables when creating and editing the record here is the code

<?php

class ParticipantController extends Controller
{

    /**
     * Store a newly created resource in storage.
     */
    public function create(Participant $participant)
    {
        $this->authorize('create',$participant);

        $events = Event::get_name_and_id();
        $wards =Ward::get_name_and_id();
        $individuals = Individual::get_name_and_id();
        $organizations = Organization::get_name_and_id();
        $roles = ParticipantRole::get_name_and_id();
        $groups = Group::get_name_and_id();

        return view('participants.create', compact('events','wards','individuals','organizations','participant','roles','groups'));
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Participant $participant)
    {
        $events = Event::get_name_and_id();
        $wards =Ward::get_name_and_id();
        $individuals = Individual::get_name_and_id();
        $organizations = Organization::get_name_and_id();
        $roles = ParticipantRole::get_name_and_id();
        $groups = Group::get_name_and_id();

        return view('participants.edit', compact('events','wards','individuals','organizations','participant','roles','groups'));
    }

}

Ass you can see from the code the form is getting data from 6 tables as dropdowns, here is how managed to do it. It is working fine but it's too much to read and understand

Upvotes: 0

Views: 93

Answers (1)

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

You may refactor redundant code in separate method like

class ParticipantController extends Controller
{

    public function populate($function_name, $participant) {
      $events = Event::get_name_and_id();
      $wards =Ward::get_name_and_id();
      $individuals = Individual::get_name_and_id();
      $organizations = Organization::get_name_and_id();
      $roles = ParticipantRole::get_name_and_id();
      $groups = Group::get_name_and_id();

      $data = compact('events','wards','individuals','organizations','roles' ,'groups', 'participant');
      return view('participants.' . $function_name , $data);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function create(Participant $participant) {

        $this->authorize('create',$participant);
        return $this->populate(__FUNCTION__, $participant);
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Participant $participant) {

       return $this->populate(__FUNCTION__, $participant);
    }

}

Upvotes: 1

Related Questions