使用laravel中间件返回数据

时间:2019-10-08 22:34:05

标签: php laravel

我正在尝试使用中间件类从数据库检索导航栏数据,以便我可以在应用程序中的任何位置访问它 数据正常,但类将数据作为ajax响应打印而不是将其作为数组传递 当我尝试导航应用程序中的任何路线时,它会打印出数据并消失并且未显示正确的视图

 <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;
use App\Navigation;
use App\PrimaryNavigation ;
use Illuminate\Http\Request;
class NavigationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $mainNavi = Navigation::with('PrimaryNavigation')->get() ;
        $subNavi = PrimaryNavigation::with('SubNavigation')->get() ;
        $navigation = [
            'main' => $mainNavi,
            'sub' =>$subNavi
        ];
        return Response($navigation);

    }
}

在内核类中注册的中间件类

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \App\Http\Middleware\NavigationMiddleware::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

1 个答案:

答案 0 :(得分:3)

使用中间件来做不是一个好主意,  使用视图作曲家或..., 另请参阅this topic