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 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services