Laravel: object or other structures (array, json..) to the view?

前端 未结 1 627
旧巷少年郎
旧巷少年郎 2021-01-07 01:01

There are several ways you may pass data to a Laravel Blade view.

In this savvy discussion Laravel hidden attributes. e.g. Password - security Antonio Carlos Ribeiro

相关标签:
1条回答
  • 2021-01-07 02:02

    If you use following approach

    $users = User::all();
    return View::make('users')->with('users', $users);
    

    You will get a collection of User objects in your model and can use a loop to print out all the User objects and it's fine, what risk could be doing this, it's upon you, so you should know what should do but if you don't want to pass a collection object then it's also possible to pass only an array of arrays using:

    $users = User::all()->toArray();
    return View::make('users')->with('users', $users);
    

    So, you'll get an array of arrays in the view where each child array will contain a perticular user's details. The array may look something like this:

    array (size=2)
      0 => 
        array (size=5)
          'id' => int 1
          'username' => string 'heera' (length=5)
          'email' => string 'heerasheikh@ymail.com' (length=21)
          'created_at' => string '2014-01-20 06:10:53' (length=19)
          'updated_at' => string '2014-01-23 10:23:50' (length=19)
      1 => 
        array (size=5)
        'id' => int 2
        'username' => string 'usman' (length=5)
        'email' => string 'mdusyl@yahoo.com' (length=16)
        'created_at' => string '2014-01-20 06:10:53' (length=19)
        'updated_at' => string '2014-01-20 09:06:23' (length=19)
    

    But, you can use the Laravel's traditional way and there is no risk at all. Don't follow something blindly, use your sense and ask yourself, what risk it may rise for you. You are only about to loop the collection, nothing else. Now, the choice is your's, if you pass the collection then you can use object notation, i.e. $user->username but if you pass an array then you have to use something like $user['username'], that's it.

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