Laravel - Pass more than one variable to view

前端 未结 11 1544
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 18:54

I have this site and one of its pages creates a simple list of people from the database. I need to add one specific person to a variable I can access.

How do I modif

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 19:17

    This is how you do it:

    function view($view)
    {
        $ms = Person::where('name', '=', 'Foo Bar')->first();
    
        $persons = Person::order_by('list_order', 'ASC')->get();
    
        return $view->with('persons', $persons)->with('ms', $ms);
    }
    

    You can also use compact():

    function view($view)
    {
        $ms = Person::where('name', '=', 'Foo Bar')->first();
    
        $persons = Person::order_by('list_order', 'ASC')->get();
    
        return $view->with(compact('persons', 'ms'));
    }
    

    Or do it in one line:

    function view($view)
    {
        return $view
                ->with('ms', Person::where('name', '=', 'Foo Bar')->first())
                ->with('persons', Person::order_by('list_order', 'ASC')->get());
    }
    

    Or even send it as an array:

    function view($view)
    {
        $ms = Person::where('name', '=', 'Foo Bar')->first();
    
        $persons = Person::order_by('list_order', 'ASC')->get();
    
        return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
    }
    

    But, in this case, you would have to access them this way:

    {{ $data['ms'] }}
    

提交回复
热议问题