Laravel上一个和下一个记录

Dui*_*oot 22 php routing laravel laravel-4

我正在尝试创建一个页面,我可以在其中查看数据库中的所有人并对其进行编辑.我做了一个表格,我从某些字段的数据库填写数据.

我想通过Next和Previous按钮浏览它们.

为了生成下一步,我必须使用大于当前ID的ID来加载下一个配置文件.

为了生成上一步,我必须将ID小于当前的ID以加载先前的配置文件.

我的路线:

Route::get('users/{id}','UserController@show');
Run Code Online (Sandbox Code Playgroud)

控制器:

public function show($id)
    {

        $input = User::find($id);

        // If a user clicks next this one should be executed.
        $input = User::where('id', '>', $id)->firstOrFail();



        echo '<pre>';

        dd($input);

        echo '</pre>';

        return View::make('hello')->with('input', $input);
    }
Run Code Online (Sandbox Code Playgroud)

查看: 按钮:

<a href="{{ URL::to( 'users/' . $input->id ) }}">Next</a>
Run Code Online (Sandbox Code Playgroud)

获取当前ID并增加它的最佳方法是什么?

小智 74

以下是您从@ ridecar2链接派生的更新控制器和视图文件,

控制器:

public function show($id)
{

    // get the current user
    $user = User::find($id);

    // get previous user id
    $previous = User::where('id', '<', $user->id)->max('id');

    // get next user id
    $next = User::where('id', '>', $user->id)->min('id');

    return View::make('users.show')->with('previous', $previous)->with('next', $next);
}
Run Code Online (Sandbox Code Playgroud)

视图:

<a href="{{ URL::to( 'users/' . $previous ) }}">Previous</a>
<a href="{{ URL::to( 'users/' . $next ) }}">Next</a>
Run Code Online (Sandbox Code Playgroud)


Ali*_*ebi 30

// in your model file
public function next(){
    // get next user
    return User::where('id', '>', $this->id)->orderBy('id','asc')->first();

}
public  function previous(){
    // get previous  user
    return User::where('id', '<', $this->id)->orderBy('id','desc')->first();

}
// in your controller file
$user = User::find(5); 
// a clean object that can be used anywhere
$user->next();
$user->previous();
Run Code Online (Sandbox Code Playgroud)

  • 为什么已经有`-&gt; first()`时为什么使用`-&gt; get()`? (2认同)

Shr*_*hal 8

在你的App\Models\User.php

...
protected $appends = ['next', 'previous'];

public function getNextAttribute()
{
    return $this->where('id', '>', $this->id)->orderBy('id','asc')->first();
}

public function getPreviousAttribute()
{
    return $this->where('id', '<', $this->id)->orderBy('id','asc')->first();
}
Run Code Online (Sandbox Code Playgroud)

在你的控制器中你可以简单地这样做:

public function show(User $user)
{
    return View::make('users.show')
    ->with('user', $user)
    ->with('previous', $user->previous)
    ->with('next', $user->next);
}
Run Code Online (Sandbox Code Playgroud)