laravel compact() and ->with()

后端 未结 7 1397
梦谈多话
梦谈多话 2020-11-30 07:17

I have a piece of code and I\'m trying to find out why one variation works and the other doesn\'t.

return View::make(\'gameworlds.mygame\', compact(\'fixture         


        
相关标签:
7条回答
  • 2020-11-30 07:56

    the best way for me :

        $data=[
    'var1'=>'something',
    'var2'=>'something',
    'var3'=>'something',
          ];
    return View::make('view',$data);
    
    0 讨论(0)
  • 2020-11-30 07:59

    You can pass array of variables to the compact as an arguement eg:

    return view('yourView', compact(['var1','var2',....'varN']));
    

    in view: if var1 is an object you can use it something like this

    @foreach($var1 as $singleVar1)
        {{$singleVar1->property}}
    @endforeach
    

    incase of single variable you can simply

    {{$var2}}
    

    i have done this several times without any issues

    0 讨论(0)
  • 2020-11-30 08:09
    Route::get('/', function () {
        return view('greeting', ['name' => 'James']);
    });
    <html>
        <body>
            <h1>Hello, {{ $name }}</h1>
        </body>
    </html>
    

    or

    public function index($id)
    {
        $category = Category::find($id);
        $topics = $category->getTopicPaginator();
        $message = Message::find(1);
    
        // here I would just use "->with([$category, $topics, $message])"
        return View::make('category.index')->with(compact('category', 'topics', 'message'));
    }
    
    0 讨论(0)
  • 2020-11-30 08:14

    I just wanted to hop in here and correct (suggest alternative) to the previous answer....

    You can actually use compact in the same way, however a lot neater for example...

    return View::make('gameworlds.mygame', compact(array('fixtures', 'teams', 'selections')));
    

    Or if you are using PHP > 5.4

    return View::make('gameworlds.mygame', compact(['fixtures', 'teams', 'selections']));
    

    This is far neater, and still allows for readability when reviewing what the application does ;)

    0 讨论(0)
  • 2020-11-30 08:14

    Laravel Framework 5.6.26

    return more than one array then we use compact('array1', 'array2', 'array3', ...) to return view.

    viewblade is the frontend (view) blade.

    return view('viewblade', compact('view1','view2','view3','view4'));
    
    0 讨论(0)
  • 2020-11-30 08:20

    I was able to use

    return View::make('myviewfolder.myview', compact('view1','view2','view3'));
    

    I don't know if it's because I am using PHP 5.5 it works great :)

    0 讨论(0)
提交回复
热议问题