【问题标题】:How to display edit/delete buttons to the user that made that post?如何向发布该帖子的用户显示编辑/删除按钮?
【发布时间】:2023-03-09 22:52:01
【问题描述】:

我正在使用 Laravel 和 VueJS 开发一个简单的论坛。在显示属于该线程的所有帖子的线程视图上,我只想向登录用户发布的那些帖子显示编辑和删除按钮。因此,用户可以编辑和删除自己的帖子,但不能编辑和删除其他人。我已经搜索了 Laravel 和 VueJS 文档,以及 Laracasts 论坛和这里......但对我没有任何帮助(不确定我做错了什么)。

我同时使用 Laravel 的刀片模板和 Vue 组件。这是我的代码:

thread.blade.php:

@section('content')
<div class="header">
    <h1>this is a thread</h1>
    <forum-search ></forum-search>
</div>
<div class="container-block">
    <thread :userId="{{ auth()->id() }}"></thread>
</div>
@endsection

thread.vue:

<template>
<!-- display this block of code ONLY when the user is logged in -->
  <div style="margin-bottom: 10px" v-if="userId == post.user_id">
    <!-- edit/delete buttons -->
  </div>
</template> 

<script>
  export default {
    name: 'thread',
    components: { quillEditor },
    props: ['userId'],
    data(){}
</script>

我尝试了几种组合 &lt;thread userId="{{ auth()-&gt;id }}"&gt;&lt;/thread&gt;、&lt;thread userId="{{ auth()-&gt;id() }}"&gt;&lt;/thread&gt;、&lt;thread userId="{{ Auth::user()-&gt;id }}"&gt;&lt;/thread&gt; 或 &lt;thread userId="{{ Auth::id() }}"&gt;&lt;/thread&gt;,正如下面帖子中的人所建议的那样......但仍然没有按我的预期工作。有什么想法吗?

Laracast:https://laracasts.com/discuss/channels/vue/i-want-to-show-delete-button-only-to-its-post-owner-in-vuejs StackOverflow:How to get current authenticated user id using Vuejs and Laravel?

【问题讨论】:

  • 使用&lt;thread :userId="{{ auth()-&gt;id() }}"&gt;&lt;/thread&gt;你得到了什么?
  • post.user_id 设置在哪里?
  • post.user_id 来自我通过axios.get('/api/threads/' + thread_id)从我的api资源获得的json
  • @N69S - 它说“未定义用户 ID”

标签: laravel vue.js


【解决方案1】:

当我需要做这样的事情时,我通常使用这里解释的策略:https://laravel.com/docs/7.x/authorization#creating-policies

设置资源策略后,您必须按照文档中所示使用它: https://laravel.com/docs/7.x/authorization#via-blade-templates

所以在你的刀片中你将拥有

@can('edit', $resource)
    <thread></thread>
@endcan

而不是

<thread :userId="{{ auth()->id() }}"></thread>

道具将不再需要

【讨论】:

  • 对我来说似乎很奇怪...您是否向我们展示了组件中的所有代码?因为我写它的方式意味着只有线程所有者才能看到它......这不是它的工作方式 IMO
  • 我只是展示了我认为相关的代码;在模板标签之间,我确实有一个 v-for loop (post, index) in thread.posts 来显示线程中的所有帖子
  • 抱歉,您的回答和我的回答之间有时间,我星期六很忙。这是否解决了您的问题?
  • 它有效,但并不完全符合我的要求......我可能没有解释我想要做得足够好。我在另一篇文章中找到了替代答案。最终对我有用的是:&lt;thread :auth_user='@json($auth_user)'&gt;&lt;/thread&gt; 在我的thread.blade.php 模板上,以及在 thread.vue 按钮内的v-if="auth_user.id === post.user.id",我只想显示给拥有用户的帖子。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
相关资源
最近更新 更多