duanji7182 2018-08-29 17:30
浏览 66
已采纳

Laravel:如何在控制器的几种方法中重用代码片段

I am building a form in order to both create and edit records.

Since I am using a lot of relational information (tables) from several catalogs and shown in the for as a select box (Select2), I need to retrieve all the data to be shown in those HTML select tags.

So, let's say that in my controller in the create() method, I call that info like so:

create() method of MyController.php:

public function create(Token $token){
    //Tags
    $universities      = University::orderBy('name')->get();
    $countries         = Country::orderBy('name')->get();
    $programs      = Program::orderBy('name')->get();
    //... and many more

    return view('my.form.create',[
        'universities' =>  $universities,
        'countries'    =>  $countries,
        'programs'     =>  $programs,
        'token'        =>  $token
    ]);
}

How do I do to reuse that piece of code //Tags

//Tags
$universities      = University::orderBy('name')->get();
$countries         = Country::orderBy('name')->get();
$programs      = Program::orderBy('name')->get();
//... and many more

in order to reuse it for the, let's say, edit() method or other ones??

  • 写回答

3条回答 默认 最新

  • duanhe7471 2018-08-29 17:42
    关注

    You could put them in a separate method in your class that just returns the data as an array and then call that method from your create and edit methods:

    protected function getFormData()
    {
        return [
            'universities' => University::orderBy('name')->get(),
            'countries'    => Country::orderBy('name')->get(),
            'programs'     => Program::orderBy('name')->get(),
        ];
    }
    

    Then your create and edit methods would look something like:

    public function create(Token $token)
    {
        $data = $this->getFormData();
    
        return view('my.form.create', $data);
    }
    
    public function edit(Token $token)
    {
        $data = $this->getFormData();
    
        return view('my.form.edit', $data);
    }
    

    If you're not planning on adding anything to the data array then you could simply inline the call instead:

    return view('my.form.edit', $this->getFormData());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?