如何创建 SELECT * FROM `TABLE` WHERE user_id = id;在 Laravel 8

how to create SELECT * FROM `TABLE` WHERE user_id = id; in Laravel 8

我想创建一个可以显示 user_id = user_id 登录数据的页面 这是我的控制器 select 来自 table 的所有数据,我想用相应的登录用户 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

提前致谢

$posts = Post::where('user_id', $user_id)->latest()->paginate(5);

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

你可以这样做

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

其中Auth::id()当前登录用户的id。

或有关系

Auth::user()->posts()->->latest()->paginate(5);

你的代码应该是这样的

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);
}