如何传递资源来查看?

问题描述 投票:0回答:4

我是 Laravel 的新手。我想知道如何将资源集合中的数据结果传递给查看。我在教程中看到,如果我没有使用资源,那么我可以简单地像这样返回来查看。

return view('articles.index')->with('posts', $posts);

我正在练习使用资源收集,我不知道如何返回查看。

public function index()
{
    $articles = Article::all();
    return ArticleResource::collection($articles);
}

我尝试使用以下将数据返回到视图,但我无法显示该数据。

return view('articles.index')->with('articles', ArticleResource::collection($articles));
php laravel-5 laravel-5.6
4个回答
4
投票
'article' => (new ArticleResource($article))->resolve(),

考虑这样它就变成了一个数组。


1
投票

您可以通过创建其对象来传递资源集合。

$data = [ 
    'articles' => new ArticleResource::collection($articles)
]

return view('articles.index')->with('data', $data);

在你的刀片中使用它就像

{{ json_encode($articles) }}

0
投票

您可以在blade视图

页面上使用您的
资源响应(集合)。像这样。

在控制器上

 $data  =  User::where('id',Auth::id())->first();
 $resumeReso  = new  ResumeViewAllRes($data);
 return view("Resume.viewAll")->with(['data'=>(object)$resumeReso->toArray($request)]);

我在With()上使用了

Array
,因为也许将来我必须传递更多数据。 您的资源文件将像我们使用的
Collection
一样旧。所以我没有在这里提到该代码。

因此,在此之后,您可以轻松地访问Blade

文件中的
Object中的任何变量。


0
投票

你可以这样做

public function index()
{
    $articles = ArticleResource::collection($articles);
    
    return view('articles.index', compact('articles'));
}

然后在你的刀片中你可以使用像这样的articles变量

@foreach(json_decode(json_encode($files)) as $article)
   // $article->data_here;
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.