Livewire retrieve Data from a relation manyToMany - php

in my blog project using livewire, i have a relationship manyToMany between tables posts & tags using a pivot table call post_tag
when i want to edit a post , in the modal i get all the data from posts table using -> wire:model.defer="post.body" ( we're using the Post model)
for the tags, i'm using a foreach to cycling through all the tags but how to get the tags associates to the post ?
Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = ['id', 'created_at', 'updated_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
use HasFactory;
protected $guarded = ['id', 'created_at', 'updated_at'];
public function posts()
{
return $this->belongsToMany(Post::class);
}
}
Migration post_tag table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('tag_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
}
};
class
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class EditHideForm extends Component
{
use WithPagination;
use WithFileUploads;
public $open = false;
public $post, $image, $identificador;
public $taggs;
protected $rules = [
'post.name' => 'required|max:100',
'post.slug' => 'required',
'post.body' => 'required',
'post.status' => 'required',
'post.user_id' => 'required',
'post.category_id' => 'required',
'post.image' => 'required',
'tagss' => 'required'
];
public function mount(Post $post)
{
$this->post = $post;
$this->tagss = $post->tags->toArray();
$this->identificador = rand();
}
public function save()
{
$this->validate();
$this->post->save();
/* codigo para borrar la foto Aqui */
$this->post->tags()->sync($this->tagss);
$this->reset(['open']);
$this->emitTo('show-post', 'render');
}
public function render()
{
$categories = Category::all();
$tags = Tag::all();
return view('livewire.edit-hide-form', compact('categories', 'tags'));
}
}
View
<div class="mb-2">
#auth
#if (auth()->user()->id === $post->user->id)
<x-jet-button wire:click="$set('open', true)">
Editar
</x-jet-button>
<x-jet-danger-button>
Eliminar
</x-jet-danger-button>
#endif
#endauth
</div>
<x-jet-dialog-modal wire:model="open" id="commentModal">
<x-slot name="title">
<h1 class="text-2xl mb-4">Edita tu post</h1>
</x-slot>
<x-slot name="content">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="container bg-white border-b border-gray-200 shadow-lg mx-auto justify-center px-4 py-2 ">
<section id="contact-us">
<div wire:loading wire:target='image'
class="bg-red-100 border border-red-400 text-xl font-normal max-w-full flex-initial">
<div class="py-2">
<p class="ml-2">Cargando la imagen</p>
<div class="text-sm font-base">
<p class="ml-2">Espero unos instantes mientras termine el proceso...</p>
</div>
</div>
</div>
#if ($image)
<img class="mb-4" src="{{ $image->temporaryUrl() }}" alt="">
#else
<img src="{{ Storage::url($post->image) }}" alt="">
#endif
<input class="hidden" wire:model="id_user" type="text" id="id" name="user_id" value={{
Auth::user()->id }}" />
<div>
<x-jet-label for="name" value="{{ __('Título') }}" />
<x-jet-input id="slug-source" class="block mt-1 mb-2 w-full" wire:model.defer="post.name"
type="text" name="name" required autofocus autocomplete="name" />
<x-jet-input-error for="name" />
<x-jet-label for="slug" value="{{ __('Slug') }}" />
<x-jet-input id="slug-target" class="block mt-1 w-full" wire:model.defer="post.slug"
type="text" name="slug" :value="old('slug')" required autofocus autocomplete="slug" />
<x-jet-input-error for="slug" />
</div>
<!-- body -->
<div>
<x-jet-label for="body" class="mt-4 text-base" value="{{ __('Contenido del post') }}" />
<textarea wire:model.defer="post.body" id="editor" rows="8" name="body"></textarea>
</div>
<x-jet-input-error for="body" />
<div class="mt-2 center justify-center mx-auto">
<!-- Image -->
<x-jet-label for="url" value="{{ __('Imagen') }}" />
<input type="file" id="image" name="image" class="mb-2" wire:model.defer="post.image" />
<x-jet-input-error for="image" />
</div>
<div>
<!-- Drop Down-->
<x-jet-label for="categories" value="{{ __('Categoría') }}" />
<select name="category_id" class="block font-medium text-sm text-gray-700" id="categories"
wire:model.defer="post.category_id">
<option selected disabled>opciones </option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<br>
<div>
<x-jet-label for="tags" value="{{ __('Etiquetas') }}" />
#foreach ($tags as $tag)
<label for="tagss"
class="relative flex-inline items-center isolate p-2 mr-4 mb-2 rounded-2xl">
<input wire:model.defer="tagss" value={{ $tag->id }} type="checkbox" class="relative
peer z-20 text-blue-600 rounded-md focus:ring-0" />
<span class="ml-1 relative z-20">{{ $tag->name }}</span>
</label>
#endforeach
</div>
<br>
<x-jet-label for="status" value="{{ __('Status') }}" />
<div class="flex">
<div class="inline-block rounded-lg">
Borrador <input type="radio" value=1 wire:model.defer="post.status" id="borrador" />
</div>
<div class="inline-block rounded-lg ml-4">
Publicado <input type="radio" value=2 wire:model.defer="post.status" name="publicado"
id="publicado" />
</div>
</div>
</section>
</div>
</div>
</x-slot>
<x-slot name='footer'>
<x-jet-secondary-button wire:click="$set('open', false)">
Cancelar
</x-jet-secondary-button>
<x-jet-danger-button wire:click="save">
Actualizar
</x-jet-danger-button>
</x-slot>
</x-jet-dialog-modal>
#push('js')
<script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then(function(editor){
editor.model.document.on('change:data', () => {
#this.set('body', editor.getData());
})
})
.catch( error => {
console.error( error );
} );
</script>
#endpush
</div>
I would appreciate any help or advice, thanks

Charles, I wrote a POC (Proof of concept) for this problem and just found that it's related to a typo, haha.
You have the public property taggs and then you're assigning $this->tagss, that's why livewire wasn't rendering the checkboxes correctly.
I would recommend you to switch to a more verbose property like tagsSelected instead of taggs (or tagss).

Related

Laravel: Add to favourites button is duplicating because of foreach loop

For a project, I've created a method where people can add products they want to buy to a wishlist. All items in the catalog are stored and each article has a hearticon that is clickable. Once it's clicked, it's added to my database.
However, when an article is added to favourites, the icon turns red but the original transparant icon is still there. So articles whom are added to favourites all have a filled and a transparant icon, which is not how it should be done.
Here is my code:
My View:
<div class="flex flex-col justify-evenly items-center lg:flex-row flex-wrap justify-between gap-y-20 gap-x-2 lg:p-20 lg:w-12/12">
#foreach ($articles as $article)
<div class="w-8/12 lg:w-3/12 flex flex-col justify-between xl:h-100">
<form action="{{route('wishlist.store', $article->id)}}" id="wish_form" method="post">
{{csrf_field()}}
<input name="user_id" type="hidden" value="{{Auth::user()->id}}" />
<input name="article_id" type="hidden" value="{{$article->id}}" />
<button type="submit" class=""><img src="{{ 'icons/0heart.png' }}" alt="" width="25" onclick="this.form.submit()" id="emptyHeart"></button>
#foreach ($wishlists as $wishlist)
#if ($wishlist->article_id === $article->id )
<button type="submit"><img src="{{ 'icons/1heart.png' }}" alt="" width="25" onclick="this.form.submit()" id="checked"></button>
#endif
#endforeach
</form>
<div class="h-2/3 xl:h-1/3 flex justify-center items-center">
{{-- <img src="{{$article->image}}" alt="" class="h-40"> --}}
</div>
<div class="h-20 mt-2">
<h4 class="text-md text-center flex"><strong>{{ $article->title }}</strong></h4>
</div>
<div class="flex flex-row flex-wrap justify-between items-center mt-4">
<p class="p-2">{{$article->prijs}}</p>
<p>Beschikbaar via {{$article->website->title}}</p>
</div>
</div>
#endforeach
</div>
My controller:
class FilterController extends Controller
{
public function catalogus(Request $r)
{
$articles = Article::all();
$categories = Category::all();
$websites = Website::all();
$wishlists = Wishlist::all()->where('user_id',auth()->user()->id);
$list = Wishlist::all()->where('article_id', $articles->id);
dd($list);
return view('catalogus', compact('articles', 'categories', 'websites', 'wishlists', 'list'));
}
}
My model:
class Wishlist extends Model
{
protected $table = "wishlists";
protected $fillable = [
'user_id',
'article_id',
'confirmed',
'available'
];
protected $casts = [
];
public function user()
{
return $this->belongsTo(User::class);
}
public function article()
{
return $this->belongsTo(Article::class);
}
You can use contains() collection method
<form action="{{route('wishlist.store', $article->id)}}" id="wish_form" method="post">
{{csrf_field()}}
<input name="user_id" type="hidden" value="{{Auth::user()->id}}"/>
<input name="article_id" type="hidden" value="{{$article->id}}"/>
#if ($wishlists->contains('article_id', $article->id))
<button type="submit">
<img src="{{ 'icons/1heart.png' }}" alt="" width="25"
onclick="this.form.submit()" id="checked">
</button>
#else
<button type="submit" class="">
<img src="{{ 'icons/0heart.png' }}" alt="" width="25"
onclick="this.form.submit()" id="emptyHeart" />
</button>
#endif
</form>

LARAVEL: My data is not stored in my database when posted

I'm building a scrape website for my laravel project.
On my admin-page I want to be able to store multiple sorts of data like 'urls' and on another form 'categories'. So those are multiple forms on one page (not sure if that is possible..).
I wrote my function so that when my data is stored, it will refresh the page. So that worked but when I went checking in my database to verify, nothing was there and I've been setting up create functions in laravel but this one is so difficult to know where it goes wrong.
This is my code:
My admin page:
<body class="relative min-h-screen">
#include('partials.header')
<main class="">
<div class="text-center m-auto text-2xl p-4 w-fit border-b">
<h2>Welkom <strong>{{ auth()->user()->name }}</strong></h2>
</div>
<div class="gap-10 m-auto xl:w-3/5">
<div class="mt-8 min-h-screen">
<h3 class="bg-gray-100 p-4"><strong>Scrapes</strong></h3>
<div class="">
<div class="p-4 m-auto">
<form action="{{ route('admin', Auth()->user()) }}">
#csrf
<div class="flex wrap flex-row items-center justify-left my-4">
<label for="shop" class="w-2/12">Webshop:</label>
<select name="shop" id="shop" class="w-4/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100">
</select>
</div>
<div class="flex wrap flex-row items-center justify-left">
<label for="url" class="w-2/12">
Voeg een url toe:
</label>
<input type="url" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="url" id="url" placeholder="bvb.: http://dreambaby.com/speelgoed">
<button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" type="submit">Voeg link toe</button>
</div>
</form>
<form action="{{ route('admin', Auth()->user()) }}" method="POST">
#csrf
#method('PUT')
<div class="flex wrap flex-row items-center justify-left">
<label for="url" class="w-2/12">
Voeg een categorie toe:
</label>
<input type="text" required class="w-7/12 h-fit p-2 focus:outline-sky-500 rounded bg-slate-100" name="title" id="cat" placeholder="bvb.: Eten en Drinken">
<button class="w-fit bg-green-400 h-fit p-2 rounded hover:bg-green-600 hover:text-white mx-2" type="submit">toevoegen</button>
</div>
</form>
</div>
<div class="mt-8 p-4">
<p>Overzicht links:</p>
<ul>
</ul>
</div>
</div>
</div>
</div>
</main>
#include('partials.footer')
</body>
My Controller:
class AdminController extends Controller
{
public function showAdmin($id)
{
return view('admin');
}
public function storeCat(Request $request)
{
$cat = Category::create([
'title' => $request->input('title')
]);
echo('Tis gelukt');
return view('admin');
}
public function updateCat(Request $request, $id)
{
$cat = Category::where('id', $id)
->update([
'title' => $request->input('title')
]);
return back();
}
public function destroyCat(Request $request, $id)
{
$cat = Category::find($id)->first();
$cat->delete();
return back();
}
}
My Model:
class Category extends Model
{
use HasFactory;
protected $table = "categories";
protected $fillable = [
'title'
];
protected $guarded = [
'id',
'created_at',
'updated_at'
];
}
My migration:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
My Routes:
Route::get('/admin/{id}', [AdminController::class, 'showAdmin'])
->name('admin');
Route::post('/admin/{id}', [AdminController::class, 'storeCat']);
Route::put('/admin/{id}', [AdminController::class, 'updateCat']);
Route::delete('/admin/{id}', [AdminController::class, 'destroyCat']);
I found why it was not working. I just had to remove method('PUT')
But I have no clue what to do when I actually want to edit my categories..

Laravel 8 Undefined variable: comments

I am trying to build a commenting system where users are able to leave comments behind on posts.
I can save and display the post and on a page i display all post I have a form where users can leave comments behind. I am able to save the comments in the database but when I try to show the comments I get this error Undefined variable: comments (View: /var/www/resources/views/projects/comment.blade.php).
My files: Comment Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Comment extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['user_id', 'post_id', 'parent_id', 'description'];
/**
* Write Your Code..
*
* #return string
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Write Your Code..
*
* #return string
*/
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
Post Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class post extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [ 'titre',
'description',
'image',
'tag',
'video',
'status',
'user_id'];
/**
* Write Your Code..
*
* #return string
*/
public function comments()
{
return $this->hasMany(Comment::class)->whereNull('parent_id');
}
}
My CommentController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
/**
* Write Your Code..
*
* #return string
*/
public function store(Request $request)
{
$input = $request->all();
$request->validate([
'body'=>'required',
]);
$input['user_id'] = auth()->user()->id;
Comment::create($input);
return back();
}
}
post display controller
public function post_display()
{
if(Auth::id()){
$userid=Auth::user()->id;
$profile=user::find($userid);
$post=post::where('user_id',$userid)->get();
return view('user.post_display',compact('post','profile'));
}
else{
return redirect()->back();
}
}
My post display view
#include('user.head')
#include('user.create_post')
<section class="ftco-section">
<div class="container" align="center" >
#foreach($post as $posts)
#if(session()->has('message2'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
x
</button>
{{session()->get('message2')}}
</div>
#endif
<div class="col-md-8 col-xl-6 middle-wrapper">
<div class="row">
<div class="col-md-12 grid-margin">
<div class="card rounded">
<div class="card-header">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center">
<img class="img-xs rounded-circle" src="https://bootdey.com/img/Content/avatar/avatar6.png" alt="">
<div class="ml-2">
<p>{{$profile->username}}</p>
<p class="tx-11 text-muted">{{$posts->created_at}}</p>
</div>
</div>
<div class="dropdown">
#include('user.update_post')
</div>
</div>
</div>
<div class="card-body">
<h5> {{$posts->tag}}
</h5>
<h4 class="mb-3 tx-14"> {{$posts->status}}</h4>
<p class="mb-3 tx-14"> {{$posts->description}}</p>
<img class="img-fluid" src="postimage/{{$posts->image}}" alt="">
</div>
<div class="card-footer">
<div class="d-flex post-actions">
<a href="javascript:;" class="d-flex align-items-center text-muted mr-4">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart icon-md">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
</svg>
<p class="d-none d-md-block ml-2">Like</p>
</a>
<h4>Display Comments</h4>
<hr />
#include('user.comment', ['comments' => $posts->comments, 'post_id' => $posts->id])
<h4>Add comment</h4>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<textarea class="form-control" name="description"></textarea>
<input type="hidden" name="post_id" value="{{ $posts->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
</section>
#include('user.footer')
<!-- loader -->
<div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>
#include('user.script')
</body>
my comment dispaly view
#foreach($comments as $comments)
<div class="display-comment" #if($comments->parent_id != null) style="margin-left:40px;" #endif>
<strong>{{ $comments->user->name }}</strong>
<p>{{ $comments->body }}</p>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<input type="text" name="body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post_id }}" />
<input type="hidden" name="parent_id" value="{{ $comments->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Reply" />
</div>
<hr />
</form>
#include('user.comment', ['comments' => $comments->replies])
</div>
#endforeach
My comment routes:
Route::post('comment',[CommentController::class,'comment'])->name('comments.store');
whene i try to create a new laravel project and put nothing other then post and comment it work.so i don't know where is the error.

Laravel Undefined variable: todos (View: /var/www/html/resources/views/content/apps/todo/app-todo.blade.php)

I am currently trying to display todos in my app-todo view, but I keep getting the error mentioned in the title.
In my controller I have:
public function index()
{
$todos = Todo::all();
return view('content.apps.todo.app-todo', ['todos' => $todos]);
}
and in my app-todo:
<div class="todo-task-list-wrapper list-group">
<ul class="todo-task-list media-list" id="todo-task-list">
#foreach($todos as $todo)
<li class="todo-item">
<div class="todo-title-wrapper">
<div class="todo-title-area">
<i data-feather="more-vertical" class="drag-icon"></i>
<div class="title-wrapper">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="customCheck1" />
<label class="form-check-label" for="customCheck1"></label>
</div>
<span class="todo-title">Drink more water</span>
</div>
</div>
<div class="todo-item-action">
<div class="badge-wrapper me-1">
<span class="badge rounded-pill badge-light-primary">Team</span>
</div>
<small class="text-nowrap text-muted me-1">Aug 08</small>
<div class="avatar">
<img
src="{{asset('images/portrait/small/avatar-s-4.jpg')}}"
alt="user-avatar"
height="32"
width="32"
/>
</div>
</div>
</div>
</li>
#endforeach
I have tried changing the code in the controller to return view('content.apps.todo.app-todo')->with(['todos' => $todos]); and using compact('todos'); ,but I get the same error.
Update:
The model is the following:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
protected $fillable = ['todoTitleAdd','task_assigned','task_due-date','task_tag', 'task_desc'];
}
and the web.php route:
Route::resource('todos', TodoController::class);
public function index(){
$todos = Todo::all();
return view('content.apps.todo.app-todo',compact('todos'));
}

Laravel livewire checkbox options not being checked

I tried many ways of populating old checked values in edit page of livewire.
Method 1 :
public $role_id, $name, $new_permissions = [];
public function mount($id)
{
/
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->toArray();
// here new_permissions is my wire:model name in view for the checkbox input
// so I tried to initialize the new_permissions array by old_permissions array
$this->new_permissions = $old_permissions;
$this->role_id = $id;
}
Method 2 :
Manually fetched the permissions in the view and checked in_array for the old_permissions to be checked:
#php
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->toArray();
#endphp
<div class="col-md-12">
<div class="form-group">
<label class="display-block text-semibold">Select Permissions</label>
#foreach($permissions as $item)
<label class="checkbox-inline">
<input type="checkbox" wire:model="new_permissions" class="" value="{{ $item->id }}" {{ in_array($item->id, $old_permissions) ? "checked" : "" }}>
{{ $item->name }} </label>
#endforeach
</div>
</div>
In the 2nd method, my code in view source was correct, the old ones had checked in input field and the new ones didnt, but in the view the checkboxes didn't appear to be checked.
Livewire use string value instead of numeric.
To fix it convert all integers in your $old_permissions array to strings like
$old_permissions = \App\Models\UserRolePermission::where('user_role_id', $this->role_id)->pluck('permission_id')->->map(function ($permission_id) {
return strval($permission_id);
})->toArray();
Here is my solution
In View
<div class="bg-white dark:bg-primary-900 rounded-md shadow mt-2 py-3 px-2">
<h3 class="mb-2 text-gray-900 dark:text-gray-100 text-xl">Permissions</h3>
<div class="grid grid-cols-12 gap-4">
#foreach ($permissions as $permission)
<div class="col-span-6 sm:col-span-4 md:col-span-3 flex items-center space-x-2">
<input wire:model="selectedPermissions" type="checkbox" value="{{ $permission->id }}"
class="w-4 h-4 transition text-primary duration-300 rounded focus:ring-2 focus:ring-offset-0 focus:outline-none focus:ring-primary-200 dark:focus:ring-primary-700">
<label class="text-sm font-semibold text-gray-500 dark:text-gray-100">
{{ ucwords($permission->display_name) }}
</label>
</div>
#endforeach
</div>
</div>
In Livewire Component Class
public $role;
public $permissions;
public $selectedPermissions = [];
protected $listeners = ['eidtRole'];
public function mount()
{
$this->permissions = Permission::get();
}
public function eidtRole(Role $role)
{
$this->role = $role;
$this->selectedPermissions = $this->rolePermissions = $role->permissions()->pluck('id')->map(function ($id) {
return strval($id);
})->toArray();
}

Categories