Laravel post radio button - laravel

I want to send the value of the radio button to the class, the problem is that the name is different each time because I have an id to finally group it in the view, how can I refer to this name?
#foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
<form method="post" action="updateprivileges/{{$user->id}}">
#csrf
<div class="row">
<div class="col-4">
<input type="radio" value="1" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '1' ? 'checked' : '' }} > <div class="uprawnienia-margin">Administrator</div>
</div>
<div class="col-4">
<input type="radio" value="2" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '2' ? 'checked' : '' }} > <div class="uprawnienia-margin">Serwisant</div>
</div>
<div class="col-4">
<input type="radio" value="3" class="flat" name="privileges_{{ $user->id }}" {{ $user->privileges[0]['roles_id'] == '3' ? 'checked' : '' }} > <div class="uprawnienia-margin">Monter</div>
</div>
</div>
<input type="submit" name="add" class="btn btn-primary input-lg" value="Przeslij" />
</form>
</td>
</tr>
#endforeach

You have dynamic name attributes. You should change this to static ones, so you can always receive the correct value in your controller where you receive the payload. And don't forget to use the correct HTTP Method.
<form method="post" action="{{ URL::to('/updateprivileges/' . $user->id)}}">
#csrf
<input type="radio" name="privilege" value="1"> Administrator</br>
<input type="radio" name="privilege" value="2"> Serwisant</br>
<input type="radio" name="privilege" value="3"> Monter</br>
<input type="submit" value="Przeslij">
</form>
Declare the route in routes/web.php:
// put method
Route::post('updateprivileges/{id}', 'UserController#updatePrivileges');
Now, your UserController receives the privilege variable in the Request $request:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function updatePrivileges(Request $request, $id)
{
$privilege = $request->input('privilege');
dd($privilege); // dumps $privilege and dies
// more code, perhaps save the users privilege
}
}
I hope this helps.
You might want to check out Laravel Method Spoofing and Put, Post, Patch. Since you know the user (by id), you might want to switch to the PUT or PATCH method.

Related

Laravel 9 Update Form Values with controller MVC

I want to update my input values ​​in the form in my database by sending them from the route to the controller. What am I doing wrong? Can you help me? I tried the #method('PUT') method before. It's a bit confusing. I am sharing the codes. I will be very happy if you can help, thank you.
...
<div class="modal-body">
<div class="form-group text-center"
style="position: center; margin-top:3em;">
<form action="{{ 'edit-name/' . $user->id }}" method="POST"
enctype="multipart/form-data">
#csrf
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="hidden"
placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit"
class="btn-sm app-btn-secondary">{{ __('welcome.confirm') }}</button>
...
my route and controller
...
Route::get('edit-name/{id}', [HomeController::class, 'editname']);
...
...
public function editname(Request $request, $id){
dd(1);
$user= Auth::user();
dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
...
you are sending the data from modal using POST method but in your route you are using this data by GET method. I will suggest you to use POST method so that user_id will not be append in URL, so try this,
Your blade
<div class="modal-body">
<div class="form-group text-center" style="position: center; margin-top:3em;">
<form action="{{ 'edit-name' }}" method="POST" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" placeholder="{{ $user->id }}">
<label for="fname">
{{ __('welcome.fullname') }}:</label>
<input name="name1" type="text" placeholder="{{ $user->name }}">
</div>
<br>
<br>
<br>
{{-- //Name Edit Button --}}
<button type="submit" class="btn-sm app-btn-secondary">{{__('welcome.confirm') }}</button>
Your route
Route::post('/edit-name', [HomeController::class, 'editname']);
Your controller
public function editname(Request $request){
// dd(1);
$user= Auth::user();
// dd($user);
$id=$request->id;
$name=$request->input('name1');
$isUpdateSuccess = User::where('id', $id) ->update(['name1'=>$name, ]);
if($isUpdateSuccess)
echo '<h1>Update Success</h1>';
else echo '<h1>Update Failed </h1>';
}
Change action
from
action="{{ 'edit-name/'. $user->id }}"
to
action="{{ url('edit-name',$user->id) }}"

my project laravel when i click submit in form with errors in input my view refresh multiple time so i can't see message errors

this problem exist in chrome and not exist in opera
this my view code here i try to do form with validate and div with type of errors:
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="add" method="POST">
{{ csrf_field() }} <!--Securite-->
Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
Product Price <input type="text" class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>
#endsection
try this one .
this will be a function in your controller.
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'price' => 'required'
]);
if ($validator->fails()) {
return redirect('your-view-name')
->withErrors($validator)
->withInput();
}
}
Errors on view with foreach
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Your Form
<form action="{{url('/route-name')}}" method="POST">
#csrf
Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
Product Price <input type="text" class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>

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>

button disappeared after configuration laravel

hello my radiobutton disappeared after a laravel configuration they are used to modify user roles they worked for a moment and then disappeared
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Modifier <strong> {{ $user->name }}</strong></div>
<div class="card-body">
<form action="{{ route('admin.user.update', $user) }}" method="POST">
#csrf
#method('PATCH')
#foreach ($roles as $role)
<div class="form-group form-check">
#foreach ($user->roles as $userRole)
#if ($userRole->id == $role->id)
<input type="radio" class="form-check-input" name="roles[]" value="{{ $userRole }}" checked>
#else
<input type="radio" class="form-check-input" name="roles[]" value="{{ $userRole }}">
#endif
#endforeach
<label for="{{ $role->id }}" class="form-check-label">{{ $role->name }}</label>
</div>
#endforeach
<button type="submit" class="btn btn-primary">Modifier les roles</button>
</form>
You can use contains() with key and value defined:
The contains() method determines whether the collection contains a given item:
#foreach ($roles as $role)
<div class="form-group form-check">
<input type="radio" class="form-check-input" name="roles[]" value="{{ $role->id }}" {{ $user->roles->contains('id', $role->id) ? 'checked' : '' }} >
<label for="{{ $role->id }}" class="form-check-label">{{ $role->name }}</label>
</div>
#endforeach

Laravel 5.4 - Updating a resource

I'm building a blog post to learn Laravel 5.4 and am struggling to find any examples of how to update a Post anywhere.
My form is as follows
<form method="POST" action="/posts/{{ $post->id }}/edit">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input name="title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input name="description" type="text" class="form-control" id="exampleInputPassword1" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
My Routes are as follows
Route::get('/posts/{post}/edit', 'PostsController#edit');
Route::patch('/posts/{post}', 'PostsController#update');
And my controller methods are
public function edit( Post $post )
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post )
{
Post::where('id', $post)->update($request->all());
return redirect('home');
}
I get a MethodNotAllowedHTTPException error but am not sure which part / parts of this I am getting wrong.
I'm assuming it must be the point at which I'm using the PATCH function, or potentially just the way I'm mass-assigning the new values. Any help would be greatly appreciated.
you should use
{{ method_field('PATCH') }}
as your form field
and change action to
/posts/{{ $post->id }}
like this:
<form method="POST" action="/posts/{{ $post->id }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="title">Title</label>
<input name="title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input name="description" type="text" class="form-control" id="exampleInputPassword1" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
There are a couple of things you have missed out.
Firstly, as #Maraboc pointed out in the comments you need to add method spoofing as standard HTML forms only allow for GET and POST methods:
<input type="hidden" name="_method" value="PATCH">
or
{{ method_field('PATCH') }}
https://laravel.com/docs/5.4/routing#form-method-spoofing
Then you will also need to omit the "edit" uri in your forms action:
<form method="POST" action="/posts/{{ $post->id }}">
or
<form method="POST" action="{{ url('posts/' . $post->id) }}">
https://laravel.com/docs/5.4/controllers#resource-controllers
(scroll down a little bit to the Actions Handled By Resource Controller section)
You also may find it helpful to watch https://laracasts.com/series/laravel-5-from-scratch/episodes/10
Hope this helps!
When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

Resources