Displaying data in Blade template

倾然丶 夕夏残阳落幕 提交于 2020-01-06 03:23:04

问题


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"
]

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.

Thanks


回答1:


Did you make a relationship in model as so:

Project:

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

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'));

Which will nest client JSON under project.

EDIT:

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

And you will simply traverse through all the projects




回答2:


Yes.

Seeing as you created a model for projects.

You can define a relationship inside that model to clients.

It will all depend on the relationship you wish it to have. Can a project have multiple clients for example.

Assuming one project has one client.

 /**
 * Get list of clients for project
 * @return object
 */
public function client()
{
    return $this->hasOne('App\Project');
}

and then inside your blade template you can call

{{ $project->client->name }}


来源:https://stackoverflow.com/questions/36861597/displaying-data-in-blade-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!