【问题标题】:How to pass multiple values from controller to view如何将多个值从控制器传递到视图
【发布时间】:2020-02-10 16:38:18
【问题描述】:

我有一个表单,它有许多下拉列表,在创建和编辑记录时从不同的表中填充 这是代码

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

}

您可以从代码中看到表单从 6 个表中作为下拉列表获取数据,下面是如何做到这一点的。它工作正常,但阅读和理解太多了

【问题讨论】:

  • 你有什么问题?
  • 如何简化这两种方法,避免冗余??以及是否有最好的方法来获取数据并传递给视图

标签: laravel laravel-6


【解决方案1】:

您可以在单独的方法中重构冗余代码,例如

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2017-04-22
    相关资源
    最近更新 更多