Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to use Laravel policies into components

I’m trying to use Policies inside a Post Component, using Laravel. This is how I’m iterating through the posts in my page.

       @foreach($posts as $post)
            <x-post 
               :id="$post->id" 
               :title="$post->title" 
               :description="$post->description" 
               :userId="$post->user_id" 
               :img="$post->img" 
               :author="$post->user->name"/>
        @endforeach

In the post.blade.php I’m trying to use a ‘update’ policy method to define which users can see the post:

@can('update', Auth::user(), /*What shoud I pass here?*/)
      <a class="btn btn-success"href="{{route('posts.edit', $id)}}">
           <i class="bi bi-pencil"></i>
      </a>
@endcan

What should I pass as the second parameter of the policy? Normally, it would be a post variable. Since I’m already inside a post, I don’t know to proceed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could check outside the component. Something like

@foreach ($posts as $post)
    <x-post 
        :id="$post->id" 
        :title="$post->title" 
        :description="$post->description" 
        :userId="$post->user_id" 
        :img="$post->img" 
        :author="$post->user->name"
        :canUpdate="Auth::user()->can('update', $post)"/>
@endforeach
@if ($canUpdate)
    <a class="btn btn-success"href="{{ route('posts.edit', $id) }}">
        <i class="bi bi-pencil"></i>
    </a>
@endif
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading