Mark Dynamically Created Checkbox Checked using Laravel - laravel

I'm trying to develop roles and permissions in laravel. I can now make the roles work properly, however i just have an issue of marking the checkbox checked of the current permissions of the user.
This is my current controller code
$role = Role::findOrFail($id);
$perm = Role::findOrFail($id)->permissions;
$permissions = Permission::all();
return view('Roles.edit', compact('permissions', 'role', 'perm'));
and for my view
#foreach($permissions as $perms)
<div class="col-lg-12">
<div class="input-group m-input-group m-input-group--square">
<input type="checkbox" name="permission[]" value="{{ $perms->id }}" />
<label>{{ ucwords(str_replace('-', ' ', $perms->name)) }}</label>
</div>
</div>
#endforeach

First of all your variable names are really bad, so try to improve those so later you know what is going on :)
I would change this:
$perm = Role::findOrFail($id)->permissions;
to this one:
$rolePermissions = Role::findOrFail($id)->permissions;
then in your view, you will need to check if the current permission is contained in the $rolePermissions and add the checked attribute to the checkbox:
#foreach($permissions as $permission)
<div class="col-lg-12">
<div class="input-group m-input-group m-input-group--square">
<input type="checkbox" name="permission[]"
value="{{ $permission->id }}"
#if(in_array($permission->id, $rolePermissions)) checked #endif />
<label>{{ ucwords(str_replace('-', ' ', $permission->name)) }}</label>
</div>
</div>
#endforeach
I guess your $rolePermissions is a set of ids. If it is not just get the ids from the collection:
$rolePermissions = Role::findOrFail($id)->permissions->pluck('id');

Related

duplicate data in blade when send data

i´m trying to show all my roles in my edit blade and with checkbox, that this checks it´s checked if this role have this permission.
my problem it´s when send data permissions and permissions to this role, all permission name it´s duplicate.
for set roles and permission i´m using laravel-permission/spatie
in my controller i have this:
public function edit($id)
{
$role = Role::find($id);
$permissions = Permission::all();
$permissionAssigned = Role::find($id)->givePermissionTo();
return view('opciones.roles.edit', ['role' => $role, 'permissions' => $permissions,
'permissionAssigned' => $permissionAssigned["permissions"] ]);
}
and in my blade i have this:
<h3>Permissions</h3>
<div class="row flex-row justify-content-center">
#foreach($permissions as $permission)
#foreach ($permissionAssigned as $asigned)
#if($permission->name == $asigned->name)
<div class="form-check p-4">
<input class="form-check-input" checked type="checkbox" name="permission[]" value="{{ $permission->name }}" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">{{ $permission->name }}</label>
</div>
#endif
#endforeach
<div class="form-check p-4">
<input class="form-check-input" type="checkbox" name="permission[]" value="{{ $permission->name }}" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">{{ $permission->name }}</label>
</div>
#endforeach
</div>
i don´t know that i´m doing wrong. I know that i have a logic problem, but i can´t solve it.
Thanks for readme and sorry for my bad english
You just need to pass the Role with associated Permissions and all Perrmissions to compare against, from the controller.
public function edit($id)
{
$role = Role::with('permissions')->find($id);
$permissions = Permission::all();
return view('opciones.roles.edit', ['role' => $role]);
}
In the view
<h3>Permissions</h3>
<div class="row flex-row justify-content-center">
#foreach($permissions as $permission)
<div class="form-check p-4">
<input type="checkbox"
id="flexCheckDefault"
class="form-check-input"
name="permission[]"
value="{{ $permission->name }}"
#checked((old($permission->name, $role->permissions->contains('name', $permission->name)) />
<label class="form-check-label" for="flexCheckDefault">{{ $permission->name }}</label>
</div>
#endforeach
</div>

Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php)

I got an Error message
Call to a member function where() on null (View: /home/farid/blog2/resources/views/jadwalpiket/editemployeepiket.blade.php) when I'm trying to create a checkbox for the edit form page
my controllers
public function edit(Employeejadwalpiket $Employee, $id)
{
$employee = Employee::all();
$jadwalpiket = Jadwalpiket::all();
$data = Employeejadwalpiket::with('employees','jadwalpiket')->find($id);
return view('jadwalpiket.editemployeepiket', compact('Employee','employee','jadwalpiket','data'));
}
my view
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Pilih Tugas :</strong>
<div class="form-check">
#foreach ($jadwalpiket as $j)
<label class="form-check-label">
<input class="form-check-input" type="checkbox" name="jadwalpiket_id[]" value="{{ $j->id }}" #if (count($Employee->jadwalpiket->where('id', $j->id)))
checked
#endif>
{{ $j->jadwal_piket }}  
</label>
#endforeach
</div>
</div>
</div>
my web.php
Route::get('/editemployeepiket/{id}',[EmployeejadwalpiketController::class, 'edit'])->name('editemployeepiket');
Route::post('/upemployeepiket/{id}',[EmployeejadwalpiketController::class, 'update'])->name('upemployeepiket');
please help me to fix it..
Change this line
#if (count($Employee->jadwalpiket->where('id', $j->id))) checked #endif>
to
#if ($Employee->jadwalpiket()->where('id', $j->id)->count()) checked #endif>
If you use you use the query builder instead of the instance, you will avoid the error.
In all cases, you should do it differently and not call everything multiple times in your controller.

How to fill the form checkboxes with checked data from database laravel 5.8

I'm having a problem in my update Form,
I create user with multiple roles assigned using checkboxes in my form, and when I need to update a user i get all the data into my update form input fields except the checkbox fields will be empty. Is there a way that I can get the checkbox checked with the data from database ?
Here's my User Model Relationship
public function roles()
{
return $this->belongsToMany(Role::class)->withTimestamps();
}
Here's my Role Model Relationship
public function users()
{
return $this->belongsToMany(User::class)->withTimestamps();
}
Here's my Edit User Form
<form action="{{ route('users.update',['user'=>$user]) }}" method="POST">
#method('PATCH')
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" value="{{ old('name') ?? $user->name }}">
<span class="text-danger">{{ $errors->first('name') }}</span>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" value="{{ old('email') ?? $user->email }}">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group">
#foreach ($roles as $role)
<label for="role">{{ $role->name }}</label>
<input type="checkbox" name="role[{{$role->id}}]" value="{{ old($role->id) }}"
#if(in_array($role->id,old('role',[]) )) checked #endif >
#endforeach
<span class="text-danger">{{ $errors->first('role') }}</span>
</div>
#csrf
<button class="btn btn-primary" type="submit">Create</button>
</form>
Here's my Edit Function
public function edit(User $user)
{
$roles = Role::all();
return view('users.edit', compact('user', 'roles'));
}
I just wanted to know how can I pull data into my checkboxes from the database and mark them as checked
I guess you should check role id with the user role id:
#if(in_array($role->id, $user->roles->toArray())) checked #endif
Finally I found out the answer
<div class="form-group">
#foreach ($roles as $role)
<label for="role">{{ $role->name }}</label>
<input type="checkbox" name="role[]" value="{{ $role->id }}"
{{ $role->users->contains($user->id) ? 'checked' : '' }}
#if(in_array($role->id,old('role',[]))) checked #endif>
#endforeach
<span class="text-danger">{{ $errors->first('role') }}</span>
</div>

Update single field in a Profile Update Form in Laravel 5

I am trying to update a single field in my user profile form section in the Laravel app.
I can save fields correctly in DB but input values and placeholders are taking wrong values. In every hit Save, the values doesn' change, and they are taken from the last listed user profile details. In my case this is user#3. The problem is when I log in with the user's #1 credentials, value and placeholder are taken from user #3. When I log in with user #2, again from user #3. Only values of user#3 are correct and I can manipulate it with no issues for both fields.
When i update the profile fields with user#1 it saves the entered one filed, but because the 2nd filed inherits the user#3 input details it saves it in field 2 of user#1 which makes a wrong entry. I can't leave null in those fields by default. My mass assignment is guarded.
How can save/update just a single field in the blade template without affecting the other fields in the form?
My routes:
Route::get( '/profile', 'userController\\profileEdit#profileEdit')->name('profileEdit');
Route::post('/profile', 'userController\\profileEdit#update')->name('update');
My controller:
namespace App\Http\Controllers\userController;
use App\Model\Hause_users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class profileEdit extends Controller
{
function profileEdit (Request $request){
$user = Hause_users::all();
$name = $request->session()->get('name');
$request->session()->keep([request('username', 'email')]);
return view('frontview.layouts.profile',['user'=>$user])->with('username' , $name );
}
function update (Request $request){
$user = Hause_users::where('username', $request->session()->get('name'))->first();
$user->fill(['email' => request('Email')]) ;
$user->save();
$user->phone;
//dd($user->phone->phone);
if ($user->phone === null) {
$user->phone->phone->create(['phone' => request('tel')]);
}
else{
$user->phone->update(['phone' => request('tel')]);
}
return back()->withInput();
}
Blade file: `
#extends('frontview.layouts.userView')
#extends('frontview.layouts.default')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#section('title')
#endsection
#section('content')
#foreach($user as $v )
#endforeach
<h2 class="form-group col-md-6">Здравей, {{$username }} </h2>
<form class = "pb2" method="POST" name = 'profile' action='profile' >
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="email" class="form-control" name = "Email" id="inputEmail4"
value="{{$v['Email']}}"
placeholder="{{$v->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$v->phone['phone']}}"
placeholder="{{$v->phone['phone']}}"
id="example-tel-input" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity">Град</label><input type="text" class="form-control" id="inputCity">
<label for="inputCity">Квартал</label><input type="text" class="form-control" id="inputCity">
</div>
{{--<div class="col-md-6" >--}}
{{--<label for="image">Качи снимка</label>--}}
{{--<input type="file" name = "image">--}}
{{--<div>{{$errors->first('image') }}</div>--}}
{{--</div>--}}
</div>
{{--<div ><img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg"--}}
{{--class="rounded-circle z-depth-1-half avatar-pic" alt="example placeholder avatar">--}}
{{--</div>--}}
{{--<div class="d-flex justify-content-center">--}}
{{--<div class="btn btn-mdb-color btn-rounded float-left">--}}
{{--<span>Add photo</span>--}}
{{--<input type="file">--}}
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Запомни ме!
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Запази</button>
</form>
#endsection
#section('name')
{{ $username }}
#endsection
Output summary:
On img#1 are the correct entry details . This is other section not the Profile edit one. Currently loged user is U#1 but as you can see on image 2, values and placeholder of both fields are for the U#3. When i hit the blue button U#1 saves the untouched filed input of U#3. Same is when i log in with U#2.
Actually the answer here is quite simple. What i am doing wrong is that i am not passing the value of the currently logged user to the view correctly. On my profileEdit method i was using $user = Hause_users::all(); and then looping trough all id's into the view and then fetching every field. But because the view doesn know which user passes the data, the foreach always returns the last user id from the array with its input, no matter which user is currently logged in. Then the data was overridden with wrong inputs.
The solution is also simple.
Instead of $user = Hause_users::all();
i have used
$user = Hause_users::where('username', $request->session()->get('name'))->first();
and then into view i was objecting the $user variable without any loops like this:
<form class = "pb2" method="POST" name = 'profile' action='profile' >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{{--<input type="hidden" name="_method" value="PATCH">--}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="Email" class="form-control" name = "Email" id="inputEmail4"
value="{{$user->Email}}"
placeholder="{{$user->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$user->phone['phone']}}"
placeholder="{{$user->phone['phone']}}"
id="example-tel-input" >
Basically this is a detailed explanation to all that not using the built in Auth system of Laravel

Laravel 5.7 using same url action for insert and update with #yield in blade template

I am using laravel 5.7 and I am using one form for inserting and updating. In form action I want to use #yield() for laravel route to get the id for updation. Every thing is fine but I can't use #yield() method. Here is my code, problem is only in action of the form.
<form class="form-horizontal" action="{{ url('/todo/#yield('editId')') }}" method="post">
{{csrf_field()}}
#section('editMethod')
#show
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="#yield('editTitle')" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">#yield('editBody')</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
I have also checked with single and double quotes.
action="/todo/#yield('editid')"
When I use simple this method then after submitting it redirects me to localhost and with an error page not found. In laravel 5.4 it works. but not in laravel 5.7. Any help would be appreciated Thanks
Here is my edit.blade.php from where I am using the #section and #yield
#extends('Todo.create')
#section('editId',$item->id)
#section('editTitle',$item->title)
#section('editBody',$item->body)
#section('editMethod')
{{ method_field("PUT") }}
#endsection
Controller store edit and update methods are
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("todo");
}
public function edit($id)
{
$item = todo::find($id);
return view("Todo.edit",compact('item'));
}
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect("/todo");
}
To answer the OP actual question you would need to do
#section('editId', "/$item->id") or #section('editId', '/'.$item->id')
{{ url('/todo') }}#yeild('editId')
But much better to do
{{ url('/todo/'.(isset($item) ? $item->id : '')) }}
Or for PHP >= 7
{{ url('/todo/'.($item->id ?? '')) }}
As apokryfos already mentioned - #yield is thought to make reusing your templates easier.
If you simply want to determine (for example) which action should be called afterwards you should better do something like that:
#extends('Todo.create')
<form class="form-horizontal" action="/todo/{{ isset($item) ? $item->id : '' }}" method="post">
#if( ! isset($item))
{{ method_field("PUT") }}
#else
{{ method_field("PATCH") }}
{{csrf_field()}}
<fieldset>
<div class="form-group">
<div class="col-lg-10">
<input type="text" name="title" placeholder="Title" value="{{ isset($item) ? $item->title : '' }}" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" placeholder="Body" name="body" rows="5" id="textarea">{{ isset($item) ? $item->body : '' }}</textarea>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</fieldset>
</form>
Also as I remember the method field should always come first to make sure it's recognized correctly. Additionally you shouldn't need url() to generate the url I think.
No need for a second blade. Simply inject the variables directly into the template and make sure they are set before you access them. I didn't try it but I'd think that it should work.

Resources