How do I uncheck checkbox in Laravel livewire for the changes to reflect in the database? - laravel

Please I need assistance solving this problem, I am using laravel Spatie roles and permission, I want to add permissions to the role using checkboxes, so far adding permission to roles is working fine, but when editing roles if I unchecked permission for a role it doesn't reflect the changes in the database,any help will be appreciated
This is view
<!-- Modal -->
<div class="modal " id="roleModal" tabindex="-1" aria-labelledby="roleModalLabel" aria-
hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="roleModalLabel">Role</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST">
#csrf
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="role" value="{{ __('Role') }}" />
<x-jet-input id="role" type="text" class="mt-1 block w-full"
wire:model.defer="roleName" />
<x-jet-input-error for="role" class="mt-2" />
</div>
<div class="block">
<strong>Permission:</strong>
<br/>
#foreach($permissions as $key => $permission)
<x-jet-label value="{{ $permission->name }}" />
<x-jet-checkbox id="permission" value="{{$permission->id}}"
type="checkbox" class="mt-1 block " wire:model.defer="permissionId" />
<br/>
#endforeach
</div>
{{-- {{dd($permission->id)}} --}}
</form>
</div>
<div class="modal-footer">
<button type="button" class="bg-red-500 text-white active:bg-indigo-600 px-3 py-2
rounded outline-none focus:outline-none" wire:click="closeModal">Close</button>
#if ($editMode)
<button type="button" class="bg-indigo-500 text-white active:bg-indigo-600 px-3
py-2 rounded outline-none focus:outline-none" wire:click="updateRole">Save
changes</button>
#else
<button type="button" class="btn btn-primary" wire:click="storeRole">Create
Role</button>
#endif
</div>
</div>
This is the role livewire component
class Roles extends Component
{
public $editMode = false;
public $roleId;
public $roleName;
public $permissionId = [];
public function showEditModal($id)
{
$this->reset();
$this->editMode = true;
$this->roleId = $id;
$this->loadRole();
$this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'show']);
}
public function loadRole()
{
$role = Role::find($this->roleId);
$this->roleName = $role->name;
$this->permissionId = $role->permissions->pluck('id');
}
public function updateRole()
{
$role = Role::find($this->roleId);
$role->update(['name' => $this->roleName ]);
$role->syncPermissions($this->permissionId);
$this->reset();
$this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'hide' ]);
session()->flash('message', 'Role Updated Successfully');
}
public function deleteRole($id)
{
$role = Role::find($id);
$role->delete();
session()->flash('message', 'Role Deleted Successfully');
}
public function closeModal()
{
$this->reset();
$this->dispatchBrowserEvent('modal', ['modalId' => '#roleModal', 'actionModal' => 'hide' ]);
}
public function render()
{
$roles = Role::orderBy('id','DESC')->paginate(5);
$permissions = Permission::get();
return view('livewire.roles', ['roles' => $roles, 'permissions' => $permissions ]);
}
}

you can check this answer Retrive ids and check related boxes
#foreach($permissions as $key => $permission)
<x-jet-label value="{{ $permission->name }}" />
<x-jet-checkbox id="permission" value="{{$permission->id}}"
type="checkbox" class="mt-1 block " wire:model.defer="permissionId.{{ $permission->id }}" #if(in_array($permission->id,$permissionId)) checked #endif />
<br/>
#endforeach

Related

Laravel Livewire hide checked checkbox

in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB
I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example
but its hidding my all input checkboxes
here is my Livewire component code:
<?php
namespace App\Http\Livewire\Tasks\Types;
use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;
class TaskTypeStatusModal extends BaseForm
{
public $task_type_id = 0;
public $availableStatuses = [];
public $selectedStatuses = [];
public $selectedStatusesList = [];
public function mount($params = [])
{
$this->task_type_id = $params['task_type_id'];
$this->title = 'Edytuj statusy';
$this->availableStatuses = TaskStatus::orderBy('position')->get();
$this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
}
public function submit()
{
foreach ($this->selectedStatuses as $status) {
TaskTypeStatus::create([
'task_type_id' => $this->task_type_id,
'task_status_id' => $status,
]);
}
$this->closeFromModal();
$this->emit( 'Zapisano');
$this->emit('list:refresh');
}
public function render()
{
return view('livewire.tasks.types.task-type-status-modal',[
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
]);
}
public function reorder($list)
{
foreach ($list as $item) {
TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
}
}
public function deleteStatus($id)
{
TaskTypeStatus::find($id)->delete();
}
and here is my blade code:
<div>
<form wire:submit.prevent="submit">
<div class="modal-header">
<h5 class="modal-title">{{ $title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Wybierz statusy</h6>
#forelse($availableStatuses as $availableStatus)
<div class="form-check checkbox">
<input class="form-check-input" name="status-{{ $availableStatus->id }}" id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
wire:click="$toggle">
<label class="form-check-label" for="status-{{ $availableStatus->id }}">{{ $availableStatus->name }}</label>
</div>
#empty
<tr>
<td colspan="3">{{ __('Brak dostępnych statusów') }}</td>
</tr>
#endforelse
<hr>
<h6>Dodane statusy</h6>
<tr><span style="color:#3c4b64;font-size: 9pt"><b>{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}</b></span></tr>
<ul class="list-group" wire:sortable="reorder">
#forelse ($selectedStatusesList as $selectedStatus)
<li class="list-group-item" value="{{ $selectedStatus->id }}" wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
<td wire:sortable.handle>{{ __($selectedStatus->taskStatus->name) }}
<div class="float-right">
<button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>
</div>
</td>
</li>
#empty
<tr>
<td colspan="3">{{ __('Brak dodanych statusów') }}</td>
</tr>
#endforelse
</ul>
</div>
<div class="modal-footer">
<button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</form>
</div>

Login form is not directing to dashboard page after user logs in

I am trying to redirect logged in users to the main dashboard view, that I've titled as "xwelcome.blade.php" temporarily.
I've attached my routes:
Route::get('xwelcome', [CustomAuthController::class, 'xwelcome']);
Route::get('login', [CustomAuthController::class, 'index'])->name('login');
Route::post('custom-login', [CustomAuthController::class, 'customLogin'])->name('login.custom');
Route::get('registration', [CustomAuthController::class, 'registration'])->name('register-user');
Route::post('custom-registration', [CustomAuthController::class, 'customRegistration'])->name('register.custom');
Route::get('logout', [CustomAuthController::class, 'logOut'])->name('logout');
This is my CustomAuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use Session;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class CustomAuthController extends Controller
{
public function index()
{
return view('auth.login');
}
public function customLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('xwelcome')
->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
public function registration()
{
return view('auth.registration');
}
public function customRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("xwelcome")->withSuccess('You have signed-in');
}
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function dashboard()
{
if(Auth::check()){
return view('xwelcome');
}
return redirect("login")->withSuccess('You are not allowed to access');
}
public function logOut() {
Session::flush();
Auth::logout();
return Redirect('login');
}
}
Login button:
<form role="form" method="post" action="{{ route('login.custom') }}">
#csrf
<div class="mt-4">
<div class="form-group">
<label class="form-control-label">Email address</label>
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="email" class="form-control" id="input-email" placeholder="name#example.com">
</div>
</div>
<div class="form-group mb-4">
<div class="d-flex align-items-center justify-content-between">
<div>
<label class="form-control-label">Password</label>
</div>
<div class="mb-2">
Lost password?
</div>
</div>
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" class="form-control" id="input-password" placeholder="Password">
<div class="input-group-append">
<span class="input-group-text">
<a href="#" data-toggle="password-text" data-target="#input-password">
<i class="fas fa-eye"></i>
</a>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
<span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>
Sign In
</button></div>
</form>
After I fill in my test account details, and press the button, I see this in my address bar
https://example.com/login?_token=0GddRaD453thhRFL7KWgEQ5DnZ3q7B4rL5gaajuM
Any help would be appreciated. Cheers
I can't see the input fields in your form!.
Have you tried to display the errors after validating the form?.
I think that you are redirected back to :
https://example.com/login?_token=0GddRaD453thhRFL7KWgEQ5DnZ3q7B4rL5gaajuM
because you are missing the input:email and input:password, what your are seeing is only the csrf token that laravel generates.
i Think issue is on button . try this out
<form role="form" method="post" action="{{ route('login.custom') }}">
#csrf
<div class="mt-4">
<button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
<span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>
Sign In
</button></div>
</form>
you are missing name attribute in your input field. the code should look like
<form role="form" method="post" action="{{ route('login.custom') }}">
#csrf
<div class="mt-4">
<div class="form-group">
<label class="form-control-label">Email address</label>
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input name="email" type="email" class="form-control" id="input-email" placeholder="name#example.com">
</div>
</div>
<div class="form-group mb-4">
<div class="d-flex align-items-center justify-content-between">
<div>
<label class="form-control-label">Password</label>
</div>
<div class="mb-2">
Lost password?
</div>
</div>
<div class="input-group input-group-merge">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input name="password" type="password" class="form-control" id="input-password" placeholder="Password">
<div class="input-group-append">
<span class="input-group-text">
<a href="#" data-toggle="password-text" data-target="#input-password">
<i class="fas fa-eye"></i>
</a>
</span>
</div>
</div>
</div>
<button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
<span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>
Sign In
</button></div>
</form>

multiple field validation using livewire ? name.0.required is working but name.*.required is not working. Please provide me solution

I want to validate all field. But It is validating only first field. Append field is not validating
multiple fields validation using livewire? name.0.required is working but name.*.required is not working.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Test extends Component
{
public $name;
public $inputs = [];
public $i = 1;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->inputs ,$i);
}
public function remove($i)
{
unset($this->inputs[$i]);
}
public function store()
{
$validatedDate = $this->validate([
'name.0' => 'required',
'name.*' => 'required',
],
[
'name.0.required' => 'name field is required',
'name.*.required' => 'name field is required',
]
);
session()->flash('message', 'Name Has Been Created Successfully.');
}
public function render()
{
return view('livewire.test');
}
}
<div>
<form class="offset-md-3">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
#error('name.0') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
</div>
</div>
</div>
#foreach($inputs as $key => $value)
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
#error('name.'.$value) <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove</button>
</div>
</div>
</div>
#endforeach
<div class="row">
<div class="col-md-12">
<button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Save</button>
</div>
</div>
</form>
</div>
This is my full code use to create multi field using livewire. I am not able to validate appended field so I need help to solve this problem. This validate first field name.0 other append field name.* does not validate.
You should use $key instead $value.
Like this:
wire:model="name.{{ $key }}"

Laravel - Submit button in delete modal form not responding

I am using Laravel-5.8 for a web application project. All other parts of the CRUD is working except the delete.
Controller
public function destroy(Request $request, $id)
{
$group = HrHolidayGroup::find($id);
$group->delete();
Session::flash('success', 'Holiday Group deleted successfully.');
return redirect()->route('hr.holiday_groups.index');
}
route/web
Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () {
Route::resource('holiday_groups', 'HrHolidayGroupsController');
});
index.blade.php
<tbody>
#foreach($groups as $key => $group)
<td>
{{$key+1}}
</td>
<td>
{{$group->group_name ?? '' }}
</td>
<td>
{{ $group->description ?? '' }}
</td>
<td>
#can('holiday_group_delete')
<a class="btn btn-xs btn-danger" data-toggle="modal" data-target="#confirm-delete{{ $group->id }}" data-original-title="Close">
span style="color:white;">{{ trans('global.delete') }}</span>
</a>
#endcan
<div class="modal fade" id="confirm-delete{{ $group->id }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Delete Holiday Group</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{route('hr.holiday_groups.destroy',['id'=>$group->id])}}" method="post">
{{ csrf_field() }}
<p>Are you sure you want to delete this Holiday Group?</p>
<div class="modal-header">
<h4>{{ $group->group_name }}</h4>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</td>
</tr>
#endforeach
delete dialogue diagram
When I clicked on Delete button on the modal form in the diagram, nothing happened. It just remain on the screen and no action is performed.
How do I get this resolved?
Thank you.
Try this
<form action="{{route('hr.holiday_groups.destroy',['id'=>$group->id])}}" method="post">
{{ csrf_field() }}
{{method_field('DELETE')}}
<p>Are you sure you want to delete this Holiday Group?</p>
<div class="modal-header">
<h4>{{ $group->group_name }}</h4>
</div>
<button type="submit" class="btn btn-danger">Delete</button>
</form>
public function destroy($id)
{
$group = HrHolidayGroup::find($id);
$group->delete();
Session::flash('success', 'Holiday Group deleted successfully.');
return redirect()->route('hr.holiday_groups.index');
}

Store and update method together using modal view laravel

I've a store and update method that I would like to use the same modal box to prompt, however I notice that the store method takes the syntax of
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts" novalidate>
whereas my update method,
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/{{ $user->id }}" novalidate>
<input type="hidden" name="_method" value="PUT">
Is there a way that I can specify which method to use depending on the option chosen, I have two buttons created, each respectively.
<button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#form">Register New User</button>
<button class="btn btn-sm btn-warning" type="button"
data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
Is there a way I can call separately using the same modal box or I have to create two duplicate modal box, one for store, the other for update?
My partial code is shown below ..
blade.php
<div class="well col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
<div class="row user-row">
<div class="col-xs-2 col-sm-3 col-md-4 col-lg-4">
<h5 style="font-weight: bold">{{ $user->name }}</h5>
</div>
<div class="col-xs-8 col-sm-8 col-md-8 col-lg-8 dropdown-user" data-for=".{{ $user->id }}">
<h5 class="glyphicon glyphicon-chevron-down text-muted pull-right"> </h5>
</div>
</div>
<div class="row user-infos {{ $user->id }}">
<div class="col-xs-12 col-sm-12 col-md-10 col-lg-10 col-xs-offset-0 col-sm-offset-0 col-md-offset-1 col-lg-offset-1">
<div class="panel panel-info">
<div class="panel-heading">
<h2 class="panel-title">User Information</h2>
</div>
<div class="panel-body">
<div class="row">
<div class=" col-md-10 col-lg-10 hidden-xs hidden-sm">
<div class="col-xs-5">User level:</div><div class="col-xs-5"> {{ $user->role->role_description }}</div>
<div class="col-xs-5">Email:</div> <div class="col-xs-5"> {{ $user->email }}</div>
<div class="col-xs-5">Phone number: </div> <div class="col-xs-5"> {{ $user->mobile }} </div>
<div class="col-xs-5">Office extension: </div> <div class="col-xs-5"> [ TO IMPLEMENT ]</div>
</div>
</div>
</div>
<div class="panel-footer">
<button class="btn btn-sm btn-warning btn--edit" type="button"
data-toggle="modal" data-target="#form">Edit <i class="glyphicon glyphicon-edit"></i></button>
<span class="pull-right">
<button class="btn btn-sm btn-danger" type="button">Inactive <i class="glyphicon glyphicon-remove"></i></button>
</span>
</div>
</div>
</div>
</div>
<input type="hidden" name="user_id" value="{{ $user->id }}" />
#endforeach
</div>
#if(Session::has('flash_message'))
<div class="alert alert-success col-xs-9 col-sm-9 col-md-9 col-lg-9 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1">
{{ Session::get('flash_message') }}
</div>
#endif
<div class="col-sm-offset-1 col-sm-2">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-md" data-toggle="modal" data-target="#form">Register New User</button>
<!-- Modal -->
<div id="form" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User Information</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form" method="POST" action="/manage_accounts/{{ $user->id }}" novalidate>
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-3" for="name">Username:</label>
<div class="col-sm-5 #if ($errors->has('name')) has-error #endif">
<input type="text" class="form-control" type="hidden" id="name" name="name" placeholder="Enter username">
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">Password:</label>
<div class="col-sm-5 #if ($errors->has('password')) has-error #endif">
<input type="password" class="form-control" type="hidden" id="password" name="password" placeholder="Enter login password">
#if ($errors->has('password')) <p class="help-block">{{ $errors->first('password') }}</p> #endif
</div>
</div>
...
controller.php
class ManageAccountsController extends Controller
{
public $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = User::orderBy('name')->get();
$roles = Role::all();
return view('manage_accounts', compact('users', 'roles'));
}
public function store(StoreUserRequest $request)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request);
Session::flash('flash_message', 'User successfully added!');
return redirect()->back();
}
public function update(StoreUserRequest $request, $id)
{
// validation already handled using this: http://laravel.com/docs/5.0/validation#form-request-validation
$this->userRepository->upsert($request, $id);
Session::flash('flash_message', 'User successfully updated!');
return redirect()->back();
}
}
class UserRepository {
public function upsert($data, $id)
{
// You will also need something like this
if(isset($id))
{
$user = User::find($id);
}
else {
$user = new User;
}
$user->name = $data['name'];
$user->email = $data['email'];
$user->password = Hash::make($data['password']);
$user->mobile = $data['mobile'];
$user->role_id = $data['role_id'];
// save our user
$user->save();
return $user;
}
}

Resources