php - 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.
解决方案
你可以!只需键入提示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 变量
推荐阅读
- java - Spring Boot 2.2.5 的 Elasticsearch 重试机制
- c - 将输入金额分解为钞票的C程序
- git - Bazel genrule:如何获取工作区目录的绝对路径?
- sql - 在 sql/postgres 中加载 csv 列表
- java - SWIG JAVA 类型映射配置
- javascript - 隐藏 p5.js 中的元素未按预期工作
- reactjs - react-router history.listener TypeScript 定义
- python - 如何在顶点枚举的浮点数和精确算术之间进行选择?
- python - 每次保存模型时,keras.Model.save 都会更改二进制文件
- python - 是或否选项