【问题标题】:how to implement the laravel pagination with auth()?如何使用 auth() 实现 laravel 分页?
【发布时间】:2020-02-04 07:42:43
【问题描述】:

我想使用分页限制我的申请人列表,但我找不到使用 auth() 的方法。有没有办法让它工作?

使用 $users = User::paginate(5);有效,但出于安全原因我想使用 auth()

已经试过了

'applicants' => auth()->user()->applicants->paginate(20)
'applicants' => auth()->user()->paginate(20)->applicants

用户.php

// Model
public function applicants()
    {
       return $this->hasMany(Scholar::class,'owner_id');
    }

ApplicantController.php

public function index()
    {

        // show all applicants
        return view('applicants/index', [
            'applicants' => auth()->user()->applicants //reutrn as collection if i dd()
        ]);
    }

foo.blade.php

{{ $applicants->links() }}
{{ $applicants->onEachSide(5)->links() }}

路由/web.php

Route::resource('applicants', 'ApplicantController');

【问题讨论】:

    标签: laravel authentication pagination


    【解决方案1】:

    分页适用于查询构建器或 Eloquent 实例。您正在尝试对集合进行分页。
    https://laravel.com/docs/6.x/pagination#basic-usage

    不带括号,此行返回一个集合。
    至此,查询已发送,数据库已返回结果。

    auth()->user()->applicants
    

    使用括号,此行返回一个查询构建器实例。
    此时,查询尚未发送到数据库。

    auth()->user()->applicants()
    

    尝试更新您的代码以解决这个小而重要的区别。

    'applicants' => auth()->user()->applicants()->paginate(20)
    
    // or some may prefer to explicitly wrap the user model
    'applicants' => (auth()->user())->applicants()->paginate(20)
    

    【讨论】:

    • 这就解决了,但这适用于php 'applicants' => auth()->user()->applicants()->paginate(20) soo 哪个更好?
    • 我倾向于包装返回特定内容(如模型)的项目,因此以后不会有任何意外,而且我发现它更容易调试。但最终我只是在自动驾驶仪上打字。在这种情况下,您可以随心所欲地编写它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多