我见过一些与我类似的问题,常见的答案是使用 View Composer 。我有一个 HomeController,它通过将查询数据传递给关联 View 来显示数据库中的文章,该 View 有效 see this image link
如您所见,有一个导航栏,它由主布局 layout.master 生成。
对于导航中的每个标题,我试图通过生成链接的 for 循环显示该部分的每篇文章。
我的代码是这样的。
public function index()
{
$loans_articles = Article::byDepartment('Loans')->get();
$digital_articles = Article::byDepartment('Digital')->get();
$consulting_articles = Article::byDepartment('Consulting')->get();
return view('welcome',
[
'loans_articles' => $loans_articles,
'digital_articles' => $digital_articles,
'consulting_articles' => $consulting_articles,
]);
}
如您所见,我正在将此数据返回到欢迎 Blade 。
在我的导航栏中我试过
@if(count($loans_articles) > 0)
@foreach($loans_articles as $ls)
<!--for each loop which grabs the articles with department Loans-->
<li><a href="/article/{{ $ls->id }}">{{ $ls->title }}</a></li>
@endforeach
@endif
但是一旦您离开主页,导航栏就不知道 $loans_article 是什么。
有没有一种干净的方法可以将此数据传递给主 Blade 导航,而无需向每个 subview 发送相同的数据?
最佳答案
我倾向于实现这一点的方法是以这种方式为每个 View 提供一个变量:
你的所有 Controller 都应该扩展一个基本 Controller ,它通常位于 app/Http/Controllers/Controller.php
.在此 Controller 中,您可以放置一些将由所有扩展 Controller 使用的代码。
在这个基本 Controller 中,您可以为所有 View 提供一个变量,就像这样......
class Controller extends BaseController
{
public function __construct()
{
// Load your objects
$loans_articles = Article::byDepartment('Loans')->get();
// Make it available to all views by sharing it
view()->share('loans_articles', $loans_articles);
}
}
您所有的 Controller 必须扩展此 Controller 以使其正常工作。
如果您的任何 Controller 有自己的构造函数,您还必须确保调用
parent::__construct()
以确保上面的代码运行。如果你的 Controller 没有自己的构造函数,你可以省略调用 parent::__construct()
.public class HomeController extends Controller
{
public function __construct()
{
parent::__construct();
// Your constructor code here..
}
}
这样你应该可以使用
$loans_articles
在你所有的观点中。
关于php - 将数据放入主 Blade - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163683/