如何在编辑数据时从 http://localhost:8000/posts/2/edit 中删除 id

How to remove id from http://localhost:8000/posts/2/edit when editing a data

我有一个显示一些数据并具有编辑功能的视图,但是当单击编辑按钮时,用户将被重定向到 http://localhost:8000/posts/2/edit,我不想要 postid出现在URL,怎么办?

<table class="table table-bordered">
    <tr>
        <th width="20px" class="text-center">No</th>
        <th>Title</th>
        <th>Content</th>
      
        <th width="280px" class="text-center">Action</th>
    </tr>
    @foreach ($posts as $post)
    <tr>
        <td class="text-center">{{ ++$i }}</td>
        <td>{{ $post->title }}</td>
        <td>{{ $post->content }}</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('Delete?')">Delete</button>
            </form>
        </td>
    </tr>
    @endforeach
</table>

这里是控制器

public function edit(Post $post)
    {
        return view('posts.edit', compact('post'));
    }

这是路线

   Route::get('/', function () {
        return view('welcome');
    });
        
    Route::resource('posts', App\Http\Controllers\PostController::class);
    Auth::routes();

提前致谢

你好 我想它会对你有所帮助

你的路线是这样的:

Route::resource('posts', App\Http\Controllers\PostController::class)->except([
    'edit'
]);

Route::resource('posts', App\Http\Controllers\PostController::class, ['only' => ['index', 'destroy', 'update' , 'create' , 'store']]);

甚至你可以单独写每条路线...

并写下你的编辑路线,分开:

Route::post('/post/edit', [App\Http\Controllers\PostController::class, "edit"])->name('post.edit');

从您的 blade 中删除 @method('DELETE') 并将此输入添加到您的 blade :

<input type="hidden" name="post_id" value="{{$post->id}}" />

并更改此设置:

public function edit(Post $post)
    {
        return view('posts.edit', compact('post'));
    }

对此:

public function edit(Request $request)
    {
       $post_id = $request->post_id;
       //write your code here
        return view('posts.edit', compact('post'));
    }

如果您想阻止用户编辑非他们创建的帖子:

public function edit(Post $post)
    {
        if(Auth::user()->id != $post->user_id) {
           throw new \Exception("Access denied", 403); 
        }
        return view('posts.edit', compact('post'));
    }

您需要使用 Auth class offcourse:

use Illuminate\Support\Facades\Auth;

您需要对删除功能执行相同的操作

为什么你不让 id 出现在 url 中。我看不出这样做的原因,因为应该有一些唯一的键来编辑 post。我看到的唯一方法是在数据库中添加一个 slug 列并将其设置为唯一。添加 post 时,将标题替换 space 为 '_' 作为 slug。确保它在验证中是唯一的。并在您的编辑和显示代码中发送 slug 而不是 id。

 route('posts.edit',$post->slug) 

不要在控制器中使用依赖注入

public function edit(  $slug)
{
          $post = Post::where('slug','=',$slug)->first();
    return view('posts.edit', compact('post'));
}