【问题标题】:how to create SELECT * FROM `TABLE` WHERE user_id = id; in Laravel 8如何创建 SELECT * FROM `TABLE` WHERE user_id = id;在 Laravel 8
【发布时间】:2021-01-28 13:50:32
【问题描述】:

我想创建一个可以显示 user_id = user_id 登录的数据的页面 这是我的控制器,它从表中选择所有数据,我想用相应的登录用户 ID 过滤它

public function staffHome()
    {
        $posts = Post::latest()->paginate(5);
        return view('staffHome', compact('posts'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

这是我的看法

 @foreach ($posts as $post)
    <tr>
        <td class="text-center">{{ ++$i }}</td>
        <td>{{ $post->title }}</td>
        <td class="text-center">
            <form action="{{ route('posts.destroy',$post->id) }}" method="POST">

                <a class="btn btn-info btn-sm" href="{{ route('posts.show',$post->id) }}">Show</a>

                <a class="btn btn-primary btn-sm" href="{{ route('posts.edit',$post->id) }}">Edit</a>

                @csrf
                @method('DELETE')

                <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Apakah Anda yakin ingin menghapus data ini?')">Delete</button>
            </form>
        </td>
    </tr>
    @endforeach

提前致谢

【问题讨论】:

  • 通过阅读 laravel 的文档,您可以找到 where() 函数...

标签: laravel laravel-8


【解决方案1】:

你的代码应该是这样的

public function staffHome()
{
   $posts = Post::where('user_id', Auth::id())->latest()->paginate(5);

    return view('staffHome', compact('posts'))->with('i', (request()->input('page', 1) - 1) * 5);
}

【讨论】:

    【解决方案2】:

    你可以这样做

    $posts = Post::where('user_id', Auth::id())-&gt;latest()-&gt;paginate(5);

    Auth::id() 当前登录用户 ID 的位置。

    或与关系

    Auth::user()-&gt;posts()-&gt;-&gt;latest()-&gt;paginate(5);

    【讨论】:

      【解决方案3】:
      $posts = Post::where('user_id', $user_id)->latest()->paginate(5);
      

      请看:https://laravel.com/docs/8.x/collections#method-where

      【讨论】:

        猜你喜欢
        • 2011-04-06
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多