Table Row in Laravel becomes clickable link - laravel

I have a question about how to make a table row in Laravel become a clickable link. I want to when the user inputs a link in the form and click save. Then the title in the table will become clickable so when the user clicks on the title, it will lead them to the page. So like in the Input Form picture, I have a field called "Hyperlink" to get the link and save it in the database. When the user clicks the button "Save", the post will be displayed in the "Post Page". I want the "Title" column in the "Post Page" to become clickable, so when the user clicks on the "Tile" (Test Link), it will lead them to the link which they did input in the "Input Form".
Input Form
Post Page
posts.blade.php
<tbody>
#foreach($posts as $post)
#if( $post->published =='publish')
<tr href="{{$post->hyperlink}}">
<td class="border px-4 py-2">{{ $post->id }}</td>
<td class="border px-4 py-2">{{ $post->title }}</td>
<td class="border px-4 py-2">{{ $post->body }}</td>
<td class="border px-4 py-2">{{ $post->author }}</td>
<td class="border px-4 py-2">{{$post->published}} </td>
<td class="border px-4 py-2">
<button wire:click="edit({{ $post->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Edit</button>
<button wire:click="delete({{ $post->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Delete</button>
</td>
</tr>
#endif
#endforeach
</tbody>
create.blade.php
<form>
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="">
<div class="mb-4">
<label for="exampleFormControlInput1" class="block text-gray-700 text-sm font-bold mb-2">Title:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
#error('title') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Body:</label>
<textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
#error('body') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Author:</label>
<textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="author" placeholder="Enter Author"></textarea>
#error('author') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Hyperlink:</label>
<textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="hyperlink" placeholder="Enter link here"></textarea>
#error('hyperlink') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="check" class="form-check-label">Publish:</label>
<input class="form-check-input" id="publish" value="publish" type="checkbox" name="published" wire:model="published">Publish</input>
<input class="form-check-input" id="no-publish" value="no-publish" type="checkbox" name="published" wire:model="published">No Publish</input>
</div>
</div>
</div>
<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">
<button wire:click.prevent="store()" type="button" class="inline-flex justify-center w-full rounded-md border border-transparent px-4 py-2 bg-green-600 text-base leading-6 font-medium text-white shadow-sm hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Save
</button>
</span>
<span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w-auto">
<button wire:click="closeModal()" type="button" class="inline-flex justify-center w-full rounded-md border border-gray-300 px-4 py-2 bg-white text-base leading-6 font-medium text-gray-700 shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Cancel
</button>
</span>
</form>
Post Schema
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('body');
$table->string('author');
$table->boolean('published')->default(0);
$table->string('hyperlink');
//create the relationship between a task and the user that created it
$table->integer('user_id')->unsigned()->index();
$table->timestamps();
});
}
app/Http/Livewire/Posts.php
use Livewire\Component;
use App\Models\Post;
use App\Models\User;
class Posts extends Component
{
public $posts, $title, $body, $post_id, $author, $published, $hyperlink;
public $isOpen = 0;
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function render()
{
$user = auth()->user();
$this->posts = $user->posts;
return view('livewire.posts');
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function create()
{
$this->resetInputFields();
$this->openModal();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function openModal()
{
$this->isOpen = true;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function closeModal()
{
$this->isOpen = false;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
private function resetInputFields(){
$this->title = '';
$this->body = '';
$this->post_id = '';
$this->author = '';
$this->published = '';
$this->hyperlink = '';
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function store()
{
$this->validate([
'title' => 'required',
'body' => 'required',
'author' => 'required',
'published' => 'required',
'hyperlink' => 'required'
]);
Post::updateOrCreate(['id' => $this->post_id], [
'title' => $this->title,
'body' => $this->body,
'author' => $this->author,
'published' => $this->published,
'hyperlink' => $this->hyperlink
]);
Page::updateOrCreate(['id' => $this->post_id], [
'title' => $this->title,
'body' => $this->body,
'publish' => $this->published
]);
session()->flash('message',
$this->post_id ? 'Post Updated Successfully.' : 'Post Created Successfully.');
$this->closeModal();
$this->resetInputFields();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function edit($id)
{
$post = Post::findOrFail($id);
$this->post_id = $id;
$this->title = $post->title;
$this->body = $post->body;
$this->author = $post->author;
$this->published = $post->published;
$this->hyperlink = $post->hyperlink;
$this->openModal();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function delete($id)
{
Post::find($id)->delete();
session()->flash('message', 'Post Deleted Successfully.');
}
}
Post Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'body', 'author', 'published', 'hyperlink'
];
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->user_id = Auth::id();
});
static::updating(function ($model) {
$model->user_id = Auth::id();
});
}
}

I solve something similar and expose this to you like one way to do it.
<td class="border px-4 py-2" onclick="window.location='{{ route('show.companies', ['company' => $company]) }}'" style="cursor: pointer;">{{ $post->title }}</td>
As you can see, when the column title is clicked, it's going to resume the function that I implement in the route...in this case act like a link to another component with data binding.

Related

I am getting an error which is shown in the image below when i am trying to update information [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 days ago.
Improve this question
I have this error please help:
Too few arguments to function App\Http\Requests\ReservationStoreRequest::Illuminate\Foundation\Providers{closure}(), 0 passed in E:\XAMPP\htdocs\resto_app\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php on line 124 and exactly 1 expected
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\TableStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\ReservationStoreRequest;
use App\Models\Reservation;
use App\Models\Table;
use Carbon\Carbon;
use Illuminate\Http\Request;
class ReservationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$reservations = Reservation::all();
return view('admin.reservations.index', compact('reservations'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
// dd($tables);
$tables = Table::where('status', TableStatus::Available)->get();
return view('admin.reservations.create', compact('tables'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(ReservationStoreRequest $request)
{
$table = Table::findorFail($request->table_id);
if($request->guest_number > $table->guest_number){
return back()->with('warning', 'Please choose the table base on guests.');
}
$request_date = Carbon::parse($request->res_date);
foreach ($table->reservations as $res) {
if ($res->res_date->format('Y-m-d') == $request_date->format('Y-m-d')) {
return back()->with('warning', 'This table base is reserved for this date.');
}
}
Reservation::create($request->validated());
return to_route('admin.reservations.index')->with('success', 'Reservation created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Reservation $reservation)
{
$tables = Table::where('status', TableStatus::Available)->get();
return view('admin.reservations.edit', compact('reservation', 'tables'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(ReservationStoreRequest $request, Reservation $reservation)
{
$table = Table::findorFail($request->table_id);
if($request->guest_number > $table->guest_number){
return back()->with('warning', 'Please choose the table base on guests.');
}
$request_date = Carbon::parse($request->res_date);
$reservations = $table->reservations()->where('id', '!=', $reservation->id)->get();
foreach ($reservations as $res) {
if ($res->res_date->format('Y-m-d') == $request_date->format('Y-m-d')) {
return back()->with('warning', 'This table base is reserved for this date.');
}
}
$reservation->update($request->validate());
return to_route('admin.reservations.index')->with('success', 'Reservation updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
this is my view
<x-admin-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="flex m-2 p-2">
<a href = "{{ route('admin.tables.index')}}"
class="px-4 py-2 bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white"
style="background-color:blue;">Tables index</a>
</div>
<div class="m-2 p-2 bg-slate-100 rounded" style="background-color:lightblue;">
<div class="space-y-8 divide-y divide-gray-200 w-1/2 mt-10">
<form method="POST" action="{{ route('admin.reservations.update', $reservation->id)}}">
#csrf
#method('PUT')
<div class="sm:col-span-6">
<label for="first_name" class="block text-sm font-medium text-gray-700">First Name</label>
<div class="mt-1">
<input type="text" id="first_name" name="first_name" value="{{ $reservation->first_name }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('first_name')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6">
<label for="last_name" class="block text-sm font-medium text-gray-700">Last Name</label>
<div class="mt-1">
<input type="text" id="last_name" name="last_name" value="{{ $reservation->last_name }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('last_name')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6">
<label for="email" class="block text-sm font-medium text-gray-700">Email</label>
<div class="mt-1">
<input type="email" id="email" name="email" value="{{ $reservation->email }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('email')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6">
<label for="tel_number" class="block text-sm font-medium text-gray-700">Phone Number</label>
<div class="mt-1">
<input type="text" id="tel_number" name="tel_number" value="{{ $reservation->tel_number }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('tel_number')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6">
<label for="res_date" class="block text-sm font-medium text-gray-700">Reservation Date</label>
<div class="mt-1">
<input type="datetime-local" id="res_date" name="res_date"
value="{{ $reservation->res_date->format('Y-m-d\TH:i:s') }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('res_date')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6">
<label for="guest_number" class="block text-sm font-medium text-gray-700"> Guest Number
</label>
<div class="mt-1">
<input type="number" id="guest_number" name="guest_number" value="{{ $reservation->guest_number }}"
class="block w-full appearance-none bg-white border border-gray-400 rounded-md py-2 px-3 text-base leading-normal transition duration-150 ease-in-out sm:text-sm sm:leading-5" />
</div>
#error('guest_number')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="sm:col-span-6 pt-5">
<label for="status" class="block text-sm font-medium text-gray-700">Table</label>
<div class="mt-1">
<select id="table_id" name="table_id" class="form-multiselect block w-full mt-1">
#foreach ($tables as $table)
<option value="{{ $table->id }}"
#selected($table->id == $reservation->table_id)>{{ $table->name }}
({{ $table->guest_number }} Guests)
</option>
#endforeach
</select>
</div>
#error('table_id')
<div class="text-sm text-red-400">{{ $message }}</div>
#enderror
</div>
<div class="mt-6 p-4">
<button type="submit"
class="px-4 py-2 bg-indigo-500 hover:bg-indigo-700 rounded-lg text-white">Update</buttom>
</div>
</form>
</div>
</div>
</div>
</div>
</x-admin-layout>
Your error is that on the update method you used $reservation->update($request->validate()) but it must be $reservation->update($request->validated()) (see validate vs validated)

AlpineJS x-for not running after x-data update

I am running into a very strange issue where I have a chatroom that should update whenever a new message is posted. Instead when I add a new message the x-data is getting updated and I can see the message there but the x-for doesnt seem to run and it never appears on the frontend. Then when I enter another message the previous message shows up on the frontend but the latest message does not show even though the x-data has been updated to reflect it.
Here is the code below:
<div
x-data="{{ json_encode(['messages' => $messages, 'messageBody' => '']) }}"
x-init="
Echo.join('chat.2')
.listen('ChatSent', (e) => {
#this.call('incomingMessage', e)
console.log(e)
})
">
<div
class="wow fadeInUp mb-10 rounded-md bg-light-bg dark:bg-dark"
data-wow-delay="0s"
>
<h3
class="border-b border-body-color border-opacity-10 py-4 px-8 text-lg font-semibold text-black dark:border-white dark:border-opacity-10 dark:text-white"
>
Chat
</h3>
<div id="chat-window" class="relative w-full p-3 overflow-y-auto h-[14rem]">
<ul class="space-y-2">
<template
x-for="message in messages"
:key="message.id"
>
<div>
<template x-if="message.user_id == {{ Auth::user()->id }}">
<li class="flex justify-end">
<div class="relative max-w-xl px-4 py-2 text-black dark:text-white bg-gray-100 dark:bg-black rounded shadow">
<span class="block" x-text="message.body"></span>
</div>
</li>
</template>
<template x-if="message.user_id != {{ Auth::user()->id }}">
<li class="flex justify-start">
<div class="relative max-w-xl px-4 py-2 text-black dark:text-white bg-blue-100 dark:bg-[#1e2a78] rounded shadow">
<span class="block" x-text="message.body"></span>
</div>
</li>
</template>
</div>
</template>
</ul>
</div>
<div class="flex items-center justify-between w-full p-3 border-t border-gray-300">
<input
#keydown.enter="
#this.call('sendMessage', messageBody)
messageBody = ''
"
x-model="messageBody"
type="text"
placeholder="Message"
class="block w-full py-2 pl-4 mx-3 bg-gray-100 dark:bg-black rounded-full outline-none focus:text-gray-700 dark:focus:text-white dark:text-white"
name="message" required />
<button
#click="
#this.call('sendMessage', messageBody)
messageBody = ''
">
<svg class="w-5 h-5 text-black dark:text-white origin-center transform rotate-90" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20" fill="currentColor">
<path
d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z" />
</svg>
</button>
</div>
#error('messageBody')
<div class="w-full p-2 text-center">
<span class="text-red-500">Message is required!</span>
</div>
#enderror
</div>
<div
class="wow fadeInUp mb-10 rounded-md bg-light-bg dark:bg-dark"
data-wow-delay="0s">
<h3
class="border-b border-body-color border-opacity-10 py-4 px-8 text-lg font-semibold text-black dark:border-white dark:border-opacity-10 dark:text-white"
>
Active Players
</h3>
<ul class="flex flex-wrap py-6 px-8">
#forelse($here as $authData)
<li>
<a
href="javascript:void(0)"
class="text-body-color-3 mr-3 mb-3 inline-flex items-center justify-center rounded-full border-[.5px] border-body-color bg-body-color bg-opacity-10 py-2 px-4 hover:border-primary hover:bg-primary hover:text-white dark:border-[#363D68] dark:bg-[#272E5C] dark:text-white dark:hover:border-primary dark:hover:bg-primary dark:hover:text-white"
>
{{ $authData['name'] }}
</a>
</li>
#empty
#endforelse
</ul>
</div>
</div>
I figure it has to be something simple I am missing and hopefully someone can point me in the right direction.
EDIT to include Livewire code:
<?php
namespace App\Http\Livewire;
use App\Events\ChatSent;
use App\Models\Chat;
use App\Models\Games;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Chatbox extends Component
{
public $game_id, $game, $chats;
public $here = [];
public $messages = [];
public function getListeners()
{
$game_id = $this->game_id;
return [
"echo-presence:chat.{$game_id},here" => 'here',
"echo-presence:chat.{$game_id},joining" => 'joining',
"echo-presence:chat.{$game_id},leaving" => 'leaving',
];
}
public function render()
{
return view('games.components.chatbox');
}
public function mount()
{
$this->game = Games::find($this->game_id);
$this->messages = Chat::
where('games_id', $this->game_id)
->with('user')
->latest()
->limit(30)
->get()
->reverse()
->values()
->toArray();
}
public function sendMessage($body)
{
if (! $body) {
$this->addError('messageBody', 'Message body is required.');
return;
}
$message = Auth::user()->chats()->create([
'body' => $body,
'games_id' => $this->game_id,
]);
$message->load('user');
broadcast(new ChatSent($message, $this->game))->toOthers();
$myMessage = $message->toArray();
$this->dispatchBrowserEvent('update-chat');
array_push($this->messages, $myMessage);
}
/**
* #param $message
*/
public function incomingMessage($message)
{
// get the hydrated model from incoming json/array.
$message = Chat::with('user')->find($message['id']);
array_push($this->messages, $message);
$this->dispatchBrowserEvent('update-chat');
}
/**
* #param $data
*/
public function here($data)
{
$this->here = $data;
}
/**
* #param $data
*/
public function leaving($data)
{
$here = collect($this->here);
$firstIndex = $here->search(function ($authData) use ($data) {
return $authData['id'] == $data['id'];
});
$here->splice($firstIndex, 1);
$this->here = $here->toArray();
}
/**
* #param $data
*/
public function joining($data)
{
$this->here[] = $data;
}
}

LARAVEL Publish and Not-publish Function has issue

I am creating a blog site, but I am having a problem as when the user clicks on the button "Create New Post," there is a form display (Create new post picture). There are two checkboxes, "Published" "Not-Published," in the form. When the user checks "Published," their post will be displayed on the Post site with the status "Published". When the user checks "Not-Published," their post will not be displayed on the Post site, but in the post database.
On the Post site, I have to radio button. The first is "Publish Posts," which will display only publish posts, the second is "All Posts," which will display all the posts include the "Not-Published" post.
I have a problem as when I click on the "Publish Posts," only the published posts will be displayed, which is good. But when I click on the "All Posts," still the published posts are displayed, I don't see any "Not-Published" posts. I checked the database and saw the "Not-Published" posts there, so why don't appear when I click "All Posts". Can someone help me to fix it?
Post site
Create new post
posts.blade.php
<button wire:click="create()" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded my-3">Create New Post</button>
#if($isOpen)
#include('livewire.create')
#endif
<div class="float-right">
<span class="mr-3 d-inline">
<label class="inline-flex items-center">
<input type="radio" class="form-radio" wire:model="viewAll" value="0">
<span class="ml-2">Publish Posts</span>
</label>
<label class="inline-flex items-center ml-6">
<input type="radio" class="form-radio" wire:model="viewAll" value="1">
<span class="ml-2">All Posts</span>
</label>
</span>
</div>
<table class="table-fixed w-full">
<thead>
<tr class="bg-gray-100">
<th class="px-4 py-2 w-20">No.</th>
<th class="px-4 py-2">Title</th>
<th class="px-4 py-2">Body</th>
<th class="px-4 py-2">Published</th>
<th class="px-4 py-2">Action</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
#if($post->published == 1)
<tr>
<td class="border px-4 py-2">{{ $post->id }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate ">{{ $post->title }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate">{{ $post->body }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate">Published</td>
<td class="border px-4 py-2">
<button class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">View</button>
#if (Auth::user()->id == $post->user_id )
<button wire:click="edit({{ $post->id }})" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Edit</button>
<button wire:click="delete({{ $post->id }})" class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">Delete</button>
#endif
</td>
</tr>
#endif
#endforeach
</tbody>
</table>
Post Schema
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string("title");
$table->string("body");
$table->boolean("published");
$table->integer("user_id")->unsigned()->index();
$table->timestamps();
});
create.blade.php
<div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full" role="dialog" aria-modal="true" aria-labelledby="modal-headline">
<form>
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="">
<div class="mb-4">
<label for="exampleFormControlInput1" class="block text-gray-700 text-sm font-bold mb-2">Title:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
#error('title') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Body:</label>
<textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
#error('body') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label class="inline-flex items-center">
<input type="radio" class="form-radio" wire:model="published" name="published" value="1">
<span class="ml-2">Published</span>
</label>
<label class="inline-flex items-center ml-6">
<input type="radio" class="form-radio" wire:model="published" name="published" value="0">
<span class="ml-2">Not-Published</span>
</label>
#error('published') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
</div>
</div>
Post Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'body', 'published', 'user_id'
];
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}
}
app/Http/Livewire/Posts.php
<?php
namespace App\Http\Livewire;
use http\Env\Request;
use Livewire\Component;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
class Posts extends Component
{
public $posts, $title, $body, $published, $post_id;
public $viewAll = 0;
public $title_filter;
public $isOpen = 0;
public function render()
{
if($this->viewAll == 0){
$this->posts = Post::where('user_id', Auth::user()->id)
->where('title', 'like', '%' . $this->title_filter. '%')
->get();
} else {
$this->posts = Post::where('user_id', Auth::user()->id)
->where('title', 'like', '%' . $this->title_filter. '%')
->get();
}
return view('livewire.posts');
}
public function create()
{
$this->resetInputFields();
$this->openModal();
}
public function openModal()
{
$this->isOpen = true;
}
public function closeModal()
{
$this->isOpen = false;
}
private function resetInputFields(){
$this->title = '';
$this->body = '';
$this->post_id = '';
}
public function store()
{
$this->validate([
'title' => 'required',
'body' => 'required',
'published' => 'required'
]);
Post::updateOrCreate(['id' => $this->post_id], [
'title' => $this->title,
'body' => $this->body,
'published' => $this->published,
'user_id' => Auth::user()->id
]);
session()->flash('message',
$this->post_id ? 'Post Updated Successfully.' : 'Post Created Successfully.');
$this->closeModal();
$this->resetInputFields();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function edit($id)
{
$post = Post::findOrFail($id);
$this->post_id = $id;
$this->title = $post->title;
$this->body = $post->body;
$this->published = $post->published;
$this->openModal();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
public function delete($id)
{
Post::find($id)->delete();
session()->flash('message', 'Post Deleted Successfully.');
}
}
try this
#foreach($posts as $post)
#if($post->published == 1)
<tr>
<td class="border px-4 py-2">{{ $post->id }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate ">{{
$post->title }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate">{{
$post->body }}</td>
<td class="border px-4 py-2 overflow-ellipsis
truncate">Published</td>
<td class="border px-4 py-2">
#elseif($post->published == 0)
<tr>
<td class="border px-4 py-2">{{ $post->id }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate ">{{
$post->title }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate">{{
$post->body }}</td>
<td class="border px-4 py-2 overflow-ellipsis
truncate">Published</td>
<td class="border px-4 py-2">
#else
<tr>
<td class="border px-4 py-2">{{ $post->id }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate ">{{
$post->title }}</td>
<td class="border px-4 py-2 overflow-ellipsis truncate">{{
$post->body }}</td>
<td class="border px-4 py-2 overflow-ellipsis
truncate">Published</td>
<td class="border px-4 py-2">
#endif
<button class="bg-green-500 hover:bg-green-700 text-white
font-bold py-2 px-4 rounded"><a href="/posts/{{ $post->id
}}">View</a></button>
#if (Auth::user()->id == $post->user_id )
<button wire:click="edit({{ $post->id }})" class="bg-
blue-500 hover:bg-blue-700 text-white font-bold py-2
px-4 rounded">Edit</button>
<button wire:click="delete({{ $post->id }})" class="bg-
red-500 hover:bg-red-700 text-white font-bold py-2
px-4 rounded">Delete</button>
#endif
</td>
</tr>
#endforeach
I think that the way you are trying to handle the radio isn't well. I recommend you try with different properties for each radiobutton like
<div>
<input type="radio" name="published" id="published" wire:model="viewPublished">
<label for="published">Published</label>
<input type="radio" name="all" id="all" wire:model="viewAll">
<label for="all">All</label>
</div>
In the component
public $viewAll = 'on';
public $viewPublished = 'off';
public function render()
{
if ($this->viewAll == 'on')
{
return view('livewire.radio-component', ['posts' => Post::all()]); // retrieve all posts
}
else
{
return view('livewire.radio-component', ['posts' => Post::where('published','=',1)->get()]); //....retrieve only published post
}
}
public function updatedViewAll()
{
if($this->viewAll == 'on')
$this->viewPublished = 'off';
}
public function updatedViewPublished()
{
if ($this->viewPublished == 'on')
$this->viewAll = 'off';
}

Laravel livewire dynamic dropdown with lots of relations on a single model

I have a fairly complex issue, I have an animal
model
class Animal extends Model
{
use HasFactory;
protected $fillable = [
"breed_ID",
"name",
"color_ID",
"eyes_color_ID",
"birth_date",
"animal_types_id",
"born_location",
"profile_picture_id",
"gender_ID",
"status",
"image",
"bio",
"lenght",
"weight",
"passport_url",
"chip_number",
"breeder_ID",
];
protected function genders(): BelongsTo
{
return $this->belongsTo(Gender::class);
}
public function borns(): BelongsTo
{
return $this->belongsTo(Born::class);
}
public function eyeColors(): BelongsTo
{
return $this->belongsTo(EyeColor::class);
}
public function colors(): BelongsTo
{
return $this->belongsTo(Color::class);
}
public function breeders(): BelongsTo
{
return $this->belongsTo(Breeder::class);
}
public function weights(): BelongsTo
{
return $this->belongsTo(Weight::class);
}
public function lengths(): BelongsTo
{
return $this->belongsTo(Length::class);
}
public function users(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function animalTypes(): BelongsTo
{
return $this->belongsTo(AnimalType::class);
}
public function images(): HasMany
{
return $this->hasMany(Image::class);
}
}
This animal has a breed, gender, color e.t.c
When a user wants to add a new animal they are presented a form, this form is a full page livewire component.
<main class="add-animal-page">
<section class="relative">
<div class="container px-4 mx-auto">
<div
class="flex flex-col justify-center w-full min-w-0 mb-6 break-words rounded-lg shadow-xl xl:flex-row bg-gray-50">
<form enctype="multipart/form-data" class="flex justify-center" wire:submit.prevent="upload">
<div class="w-full xl:w-4/6">
<div class="flex justify-center px-4 py-5 sm:p-6">
<div class="grid max-w-4xl grid-cols-6 gap-6">
<div class="col-span-6 sm:col-span-3 lg:col-span-2">
<label for="first_name" class="block text-sm font-medium text-gray-700">Name</label>
<input type="text" name="first_name" id="first_name" autocomplete="given-name"
wire:model.defer="animal.name"
class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
</div>
<div class="col-span-6 sm:col-span-6">
<label for="type" class="block text-sm font-medium text-gray-700">
Type</label>
<select wire:model="animal.breeds_id" name="breed" id="breed"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a type</option>
#foreach ($types as $type)
<option value={{ $type->id }}>{{ $type->animal_name }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="breed" class="block text-sm font-medium text-gray-700">
Breed</label>
<select wire:model="animal.breeds_id" name="breed" id="breed"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a breed</option>
#foreach ($breeds as $breed)
<option value={{ $breed->id }}>{{ $breed->breed_name }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="breed" class="block text-sm font-medium text-gray-700">
Breed</label>
<select wire:model="animal.breeds_id" name="breed" id="breed"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a breed</option>
#foreach ($breeds as $breed)
<option value={{ $breed->id }}>{{ $breed->breed_name }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="gender" class="block text-sm font-medium text-gray-700">
Gender</label>
<select wire:model="animal.genders_id" name="gender" id="gender"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a gender</option>
#foreach ($genders as $gender)
<option value={{ $gender->id }}>{{ $gender->type }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="eye_color" class="block text-sm font-medium text-gray-700">
Eye color</label>
<select wire:model="animal.eye_color_id" name="eye_color" id="eye_color"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose an eye color</option>
#foreach ($eyeColors as $eyeColor)
<option value={{ $eyeColor->id }}>{{ $eyeColor->name }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="Breeder" class="block text-sm font-medium text-gray-700">
Breeder</label>
<select wire:model="animal.breeders_id" name="Breeder" id="Breeder"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a breeder</option>
#foreach ($breeders as $breeder)
<option value={{ $breeder->id }}>{{ $breeder->name }}</option>
#endforeach
</select>
</div>
<div class="col-span-6 sm:col-span-6">
<label for="passport" class="block text-sm font-medium text-gray-700">
Passport URL</label>
<input type="text" wire:model.defer="animal.passport_url" name="passport"
id="passport" autocomplete="text"
class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
</div>
<div class="col-span-6 sm:col-span-6">
<label for="chip_number" class="block text-sm font-medium text-gray-700">
Chip number</label>
<input type="text" wire:model.defer="animal.chip_number" name="chip_number"
id="chip_number" autocomplete="chip_number"
class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
</div>
<div class="col-span-6">
<label for="bio" class="block text-sm font-medium text-gray-700">
Bio
</label>
<div class="mt-1">
<textarea wire:model.defer="animal.bio" id="bio" name="bio" rows="3"
class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
</textarea>
</div>
</div>
</div>
</div>
<div class="max-w-md mx-auto overflow-hidden rounded-lg md:max-w-xl">
<div class="md:flex">
<div class="w-full p-3 ">
<div
class="relative flex items-center justify-center h-48 bg-gray-100 border-2 border-dotted rounded-lg border-primary-light">
<div class="absolute">
<div class="flex flex-col items-center"><i
class="fa fa-folder-open fa-4x text-primary"></i> <span
class="block font-normal text-gray-400">Upload your image
here</span>
</div>
</div>
<input wire:model.defer="image" type="file"
class="w-full h-full opacity-0 cursor-pointer">
</div>
</div>
</div>
</div>
</div>
<div class="absolute bottom-0 right-0 px-6 py-3 mx-4 my-6 text-right bg-gray-50 sm:px-6">
<button type="submit"
class="inline-flex justify-center px-4 py-2 text-sm font-medium text-white border border-transparent rounded-md shadow-sm bg-primary hover:bg-primary-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
Save
</button>
</div>
</form>
</div>
</div>
</section>
</main>
The form is populated via this livewire class.
class AddAnimal extends Component
{
use WithFileUploads;
public User $user;
public Animal $animal;
public Collection $genders;
public Collection $eyeColors;
public Collection $breeds;
public Collection $colors;
public Collection $breeders;
public Collection $types;
public $image;
protected array $rules = [
'animal.name' => 'required|min:2',
'animal.eye_color_id' => 'nullable',
'animal.bio' => 'nullable',
'animal.breeds_id' => 'nullable',
'animal.genders_id' => 'nullable',
'animal.breeders_id' => 'nullable',
'animal.chip_number' => 'nullable',
'animal.passport_url' => 'nullable',
'image' => 'nullable',
];
public function mount(User $user)
{
$this->user = $user;
$this->animal = new Animal();
$this->genders = Gender::all();
$this->eyeColors = EyeColor::all();
$this->breeds = Breed::all();
$this->colors = Color::all();
$this->breeders = Breeder::all();
$this->types = AnimalType::all();
}
public function render()
{
return view('livewire.add-animal')
->layout('components.layouts.dashboard', ['title' => 'Add-animal'])
->with(['user' => $this->user, 'genders' => $this->genders, 'eyeColors' => $this->eyeColors, 'breeds' => $this->breeds, 'colors' => $this->colors, 'breeders' => $this->breeders, 'types' => $this->types]);
}
How can I make it so that my dropdowns become dynamic? e.g if a user selects dog as animal type, in the breed dropdown only relevant dog breeds should be shown, and not cats or horses. I tried using some of the online available tutorials to get me started, but could not figure it out with all the relationships going on in my models.
Since the Breed Model has an animal_type id, we can use Livewire's updated hook to check for changes on the animal type and render only breeds related to the animal type.
so in the livewire component,
class AddAnimal extends Component
{
public User $user;
public Animal $animal;
public Collection $genders;
public Collection $eyeColors;
// public Collection $breeds; we will use a computed property
public Collection $colors;
public Collection $breeders;
public Collection $types;
public $image;
// newly added variable to keep track of animal type changed
public $filters = [
'animal_type_id' => ''
];
protected array $rules = [
'animal.name' => 'required|min:2',
'animal.eye_color_id' => 'nullable',
'animal.bio' => 'nullable',
'animal.breeds_id' => 'nullable',
'animal.genders_id' => 'nullable',
'animal.breeders_id' => 'nullable',
'animal.chip_number' => 'nullable',
'animal.passport_url' => 'nullable',
'image' => 'nullable',
'animal.animal_type_id' => '', // make sure you have the rule can be left empty if its not required
];
public function mount(User $user)
{
$this->user = $user;
$this->animal = new Animal();
$this->genders = Gender::all();
$this->eyeColors = EyeColor::all();
$this->colors = Color::all();
$this->breeders = Breeder::all();
$this->types = AnimalType::all();
}
public function updatedAnimalAnimalTypeId($value)
{
$this->filters['animal_type_id'] = $value;
}
public function getBreedsProperty()
{
return Breed::when($this->filters['animal_type_id'], function($query, $animal_type_id){
return $query->where('animal_type_id', $animal_type_id);
})->get();
}
public function render()
{
return view('livewire.add-animal')
->layout('components.layouts.dashboard', ['title' => 'Add-animal'])
->with(['user' => $this->user, 'genders' => $this->genders, 'eyeColors' => $this->eyeColors, 'breeds' => $this->breeds, 'colors' => $this->colors, 'breeders' => $this->breeders, 'types' => $this->types]);
}
}
Note that I have used computed property to get the breeds.
I also have made use of when clause to avoid the null check.
so in the blade file, we just have to wire:model the animal_type_id.
....
<div class="col-span-6 sm:col-span-6">
<label for="type" class="block text-sm font-medium text-gray-700">
Type</label>
<select wire:model="animal.animal_type_id" name="animal_type_id" id="animal_type_id"
class="block w-full px-3 py-2 mt-1 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<option value="">Choose a type</option>
#foreach ($types as $type)
<option value={{ $type->id }}>{{ $type->animal_name }}</option>
#endforeach
</select>
</div>
....
Now the breeds will be rendered based on the animal type selected.
I have assumed animal_type_id is the correct column name in Animal model. if its not, please change the column name respectively.

Laravel Livewire sync($request->input)

public function modelData()
{
$user = User::create([
'name' => $this->name,
'npm' => $this->npm,
'email' => $this->email,
'jurusan' => $this->jurusan,
'fakultas' => $this->fakultas,
'password' => Hash::make($this->password),
]);
$user->roles()->sync($this->input('roles', []));
}
this is my code. please someone help me how to use request -> input in livewire
class Usermanajemen extends Component
{
public $role = [];
public $users;
public $name;
public $npm;
public $email;
public $password;
public $jurusan;
public $fakultas;
use WithPagination;
public $modalFormVisible = false;
public $modelid;
public function render()
{
$this->users = User::orderBy('created_at', 'DESC')->get();
$roles = Role::pluck('title', 'id');
return view('livewire.usermanajemen', compact('roles'));
}
public function create()
{
$this->validate();
User::create($this->modelData());
$this->modalFormVisible = false;
$this->reset();
}
public function closeModal()
{
$this->modalFormVisible = false;
}
public function createShowModal()
{
$this->resetValidation();
$this->reset();
$this->modalFormVisible = true;
}
public function mount()
{
$this->resetPage();
}
/**
* The update function.
*
* #return void
*/
public function rules()
{
return [
'name' => ['required', 'string', 'max:255'],
'npm' => ['required', 'numeric', Rule::unique('users', 'npm')->ignore($this->modelid)],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'min:6'],
'jurusan' => 'required',
'fakultas' => 'required',
];
}
/**
* The data for the model mapped
* in this component.
*
* #return void
*/
public function modelData()
{
$user = User::create([
'name' => $this->name,
'npm' => $this->npm,
'email' => $this->email,
'jurusan' => $this->jurusan,
'fakultas' => $this->fakultas,
'password' => Hash::make($this->password),
]);
$user->roles()->sync($this->role);
}
}
this is my livewire usermanajemen i change my role in create and add role=[]in public
<form>
<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="">
<div class="mb-4">
<label for="name" class="block text-gray-700 text-sm font-bold mb-2">Nama:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="name" wire:model="name">
#error('name') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="npm" class="block text-gray-700 text-sm font-bold mb-2">Npm:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="npm" wire:model="npm">
#error('npm') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="email" class="block text-gray-700 text-sm font-bold mb-2">Email:</label>
<input type="email" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" wire:model="email">
#error('email') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="password" class="block text-gray-700 text-sm font-bold mb-2">Password:</label>
<input type="password" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="password" wire:model="password">
#error('password') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="jurusan" class="block text-gray-700 text-sm font-bold mb-2">Jurusan:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="jurusan" wire:model="jurusan">
#error('jurusan') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="mb-4">
<label for="fakultas" class="block text-gray-700 text-sm font-bold mb-2">Fakultas:</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="fakultas" wire:model="fakultas">
#error('fakultas') <span class="text-red-500">{{ $message }}</span>#enderror
</div>
<div class="px-4 py-5 bg-white sm:p-6">
<label for="role" class="block font-medium text-sm text-gray-700">Roles</label>
<select wire:model = "role" name="role" id="role" class="form-multiselect block rounded-md shadow-sm mt-1 block w-full" multiple="multiple">
#foreach($roles as $id => $role)
<option value="{{ $id }}"{{ in_array($id, old('roles', [])) ? ' selected' : '' }}>{{ $role }}</option>
#endforeach
</select>
#error('roles')
<p class="text-sm text-red-600">{{ $message }}</p>
#enderror
</div>
</div>
</div>
this is my blade file for create
i change in my livewire and my blade and still error but users added
Why do you want to use request ?
You can add a property like public roles = []; in the class
and bind this property with select/checkbox ie: <select wire:model="role" multiple>
and then you can use sync like this : $user->roles()->sync($this->roles);
PS: I assumed that you already defined many to many relationship

Resources