【问题标题】:how to pass multiple table data to view in laravel 5.2如何在 laravel 5.2 中传递多个表数据以查看
【发布时间】:2016-05-18 12:36:57
【问题描述】:

我在数据库中有 3 个表,

--用户

--简介

--教育

用户模型

 public function profiledetails()
{
        return $this->hasOne('App\Profiledetails');
}

public function educationHasOne()
{
        return $this->hasOne('App\Education');
}

个人资料模型

public function user()
{
        return $this->belongsTo('App\User');
}

教育模式

public function user()
{
        return $this->belongsTo('App\User');
}

我能够存储数据。

我想在一个网页中查看所有表格数据 我使用下面的代码来实现这一点。

  public function index()
 {
 $user = Auth::user()->id;
 $profile = array(
     User::find($user)->profiledetails,
     User::find($user)->educationHasOne 
 );
 return view('profile.index', ['profile' => $profile]);
}

当使用 dd($variablename) 时,我可以看到我需要的所有必填字段,

现在,我想知道如何传递所有这些数据以在单页中查看。

【问题讨论】:

    标签: php arrays eloquent laravel-5.2 laravel-blade


    【解决方案1】:

    您可以将数组传递给视图,如下所示:

    return view('profile', ['profile' => $profile]);
    

    在视图中,可以访问$profile

    如果您需要每个数据,建议使用view composers。不错的文档 + 示例可以在这里找到:https://laravel.com/docs/5.1/views#passing-data-to-views

    【讨论】:

    • 感谢您的快速回答,我尝试了上面的代码。我收到 2 个错误 ErrorException Trying to get property of non-object。由于我的 $profile 具有所有值,为什么这不起作用return view('index',compact('profile')
    • 您错过了)。请在您的问题中发布您的完整代码。我的答案是对的,但我认为在整合时会出错。
    • 传递一个数组来查看效果很好。如果用户登录 public function index() { $user = Auth::user()->id; $profile = User::find($user)->profiledetails; $education = User::find($user)->educationHasOne; return view('profile.index',['profile' => $profile, 'education' => $education]); },我无法看到结果,因为我的视图是有界的
    • 感谢您提及view composer 部分。
    【解决方案2】:

    您可以使用@Schellingerht 答案,甚至可以使用“compact”

    $profile= 'someVar';
    return view( 'profile',compact('profile') );
    

    这里你不需要创建一个 assoc 数组。只需确保变量名称与紧凑中的字符串相同。 在您看来,您只需将其称为

    {{$profile}}
    

    【讨论】:

      【解决方案3】:

      感谢@Schellingerht,将数组传递给视图工作完美。

      当用户登录时,代码运行完美。

      下面是我的代码

      pass an array to the view
      
      public function index()
      {
      
       $user = Auth::user()->id;
       $profile   = User::find($user)->profiledetails;
      
       $education = User::find($user)->educationHasOne;
       return view('profile.index',['profile' => $profile, 'education' => $education]); 
      

      }

      【讨论】:

      • 完美! ;-) 如果每个视图都需要一些数据,请查看视图作曲家。
      猜你喜欢
      • 2021-12-29
      • 2017-01-11
      • 2017-07-30
      • 2013-12-05
      • 1970-01-01
      • 2015-11-03
      • 2021-12-05
      相关资源
      最近更新 更多