首页 > 解决方案 > Laravel View Composer Paginating with ajax

问题描述

I managed to find some resources to paginate a normal page with ajax. It's pretty easy. you can simply have this:

if($request->ajax()) {
    return [
        'posts' => view('ajax.index')->with(compact('posts'))->render(),
        'next_page' => $posts->nextPageUrl()
    ];
}

But for Composer View this won't work, since I can't have $request in View Composer. Can anybody enlighten me. Maybe there is someway to get variables inside composer, since the link for it's pagination is basicaly the current page plus the extension for next contnet.

标签: phpajaxlaravelpaginationlaravel-5.6

解决方案


你可以!只需键入提示Request类,服务容器将在运行时注入它。然后您可以访问请求对象的所有属性

use Illuminate\Http\Request;

class MyComposer 
{
    public function __construct(Request $request)
    {
        $this->request= $request;
    }

    function compose($view)
    {
        if($this->request->ajax()) {
          return [
            'posts' => view('ajax.index')->with(compact('posts'))->render(),
            'next_page' => $posts->nextPageUrl()
          ];
        }
    }

}

更新: 如果您没有将它从控制器传递到您的视图但 $category 对象仍在作曲家中使用,则会出现错误。为避免这种情况,您可以删除*并显式传递视图名称那些使用类别的视图并创建另一个声明传递那些不使用类别的视图的名称,因此您将需要两个视图合成器

//these views use category
View::composer([ 'view1','view2'], 'App\Http\ViewComposers\MyComposerWithCategory' ); 


//these views don't
View::composer([ 'view3','view4'], 'App\Http\ViewComposers\MyComposerWithoutCategory' ); 

或者您可以检查是否在 if 语句中设置了 $category 变量


推荐阅读