存在几种将变量传递给所有视图的方法。我解释了一些方法。
1.对所有需要传递变量的路由使用中间件:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
转到app/Http/Middleware/RootMiddleware.php 并执行以下示例代码:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
然后必须在app/Http/Kernel.php中注册这个中间件,并将这行'root' => RootMiddleware::class,放到protected $routeMiddleware数组中。
然后使用路由或路由组的这个中间件,例如:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
或设置为单根:
Route::get('/profile', 'ProfileController@profile')->name('profile')->middleware('RootMiddleware');
2. 使用视图编辑器将变量传递给所有视图的其他方式
转到 app/Http 并创建 Composers 文件夹并在其中创建 ProfileComposer.php,在 ProfileComposer.php 中像这样:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
现在是时候创建你的服务提供者类了,我把它命名为ComposerServiceProvider
在终端中写入此命令:php artisan make:provider ComposerServiceProvider
在成功创建 Provider 之后。 消息转到 config/app.php 并注册您的提供程序,并将此 \App\Providers\ComposerServiceProvider::class 放入 providers 数组。
现在转到app/Providers/ComposerServiceProvider.php 并执行以下操作:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
}
}
3. 可以在不创建服务提供商的情况下将您的变量共享到AppServiceProvider,转到app/Provider/AppServiceProvider.php 并执行以下操作:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
希望对你有用