laravel - Laravel如何在主模板文件中包含的所有视图中传递数据?
问题描述
我有一个主模板文件,它由不同的控制器和不同的视图调用。在页脚中显示类别列表,那么我如何从所有控制器的方法中传递数据而不在所有函数中编写代码并传递数据?
解决方案
在app/Providers/AppServiceProvider.php中获取类别 boot method
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Auth;
use DB;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
View::share('key', 'value');
Schema::defaultStringLength(191);
$categories=DB::table('categories')->get();
View::share('categories',$categories);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
$categories
现在您可以访问变量中所有视图和控制器中的类别
在您的页脚中:
@foreach($categories as $category)
<p>{{$category->name}}</p>
@endforeach
推荐阅读
- ruby-on-rails - Rails 迁移:“up”和“down”与“change”相比有什么优势?
- numpy - H2OTypeError:参数应该是一个?整数,得到 int64 [3.30.1.1]
- swagger - swagger-ui 依赖于大响应
- javascript - Heroku 上的 NodeJS REST API 后端主机崩溃
- java - 将数据从arduino发送到spring boot java
- python - 我正在尝试将 idf.py 作为 CMD 命令运行。我已经设置了我的环境变量它仍然无法识别
- asp.net-ajax - 无法使用 C# 与 Xero SDK 建立连接
- kubernetes - 如何创建由预先存在的 EBS 卷支持的 PVC/PV?
- postgresql - PostgreSQL 导出的 csv 文件无法在 ms Sql Server 数据库中读取
- c++ - Angular 8 上的 Websocket 客户端和 C++ 控制台中的服务器