在Blade模板中显示数据 [英] Displaying data in Blade template

查看:95
本文介绍了在Blade模板中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我向模板传递了一个项目列表

in my controller, I pass my template a list of projects

$projects = Project::all();
return view('projects.index', compact('projects'));

现在,一个项目有一个客户端,并且一个客户端属于一个项目.如果在我的视图中循环我的项目,我将得到以下数据

Now a Project has one client, and a client belongs to a project. If I loop my Projects within my view, I get the following data

#attributes: array:11 [▼
    "id" => "25"
    "jobNumber" => "J0001"
    "projectName" => "Some Name"
    "clientId" => "1"
    "clientContact" => "Some Contact"
    "contactEmail" => "email@email.co.uk"
    "status" => "Email"
    "deleted_at" => null
    "created_at" => "2016-04-25 14:15:19"
    "updated_at" => "2016-04-26 10:05:06"
]

如您所见,clientId为1.这链接到特定的客户端.有什么方法可以使用此ID获取客户端名称吗?我知道如何在控制器中执行此操作,但是我无法为每个具有客户端名称的项目传递变量,这将太多.就目前而言,我正在传递所有项目的视图,并且每个项目都有一个clientId.我不知何故需要以此命名.

As you can see, the clientId is 1. This links to a particular client. Is there any way to get the client name using this ID? I know how to do it in the controller, but I can't pass a variable for each project which has the clients name, this would be too much. As it stands, I am passing the view all of the projects, and each of these has a clientId. Somehow I need to get the named based off this.

谢谢

推荐答案

您是否在模型中建立了关系:

Did you make a relationship in model as so:

项目:

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

如果这样做,您只需调用Project::find($id)->client

If you did, you can get to the client you need by simply calling Project::find($id)->client

如果您想通过控制器转发它,可以这样做:

If you want to forward it through controller, you can do it like:

$projects = Project::with('client');
return view('project.index', compact('projects'));

这会将客户端JSON嵌套在项目下.

Which will nest client JSON under project.

但是,如果我理解正确,那么您的问题是在视图中显示它,而无需进行任何变量操作.如果您使用Blade作为视图,则可以使用foreach循环来实现,例如:

However if I understood correctly, your problem is displaying it in a view without the need to do hundereds of variables. If you're using blade for your views, you can do it with foreach loop like so:

@foreach($projects as $project)
    {{$project->client->name}}
@endforeach

您将只需遍历所有项目

这篇关于在Blade模板中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆