I'm creating a users management with Laravel 9, I am an administrator and I would like to change users to admins whenever I like :)
For example this user ->
I wrote this code ->
public function UpdateToAdminAction(Request $request) {
$request->validate([
'type' => 'required|exists:users',
]);
DB::table('users')->update(
['type' => $request->type]
);
return redirect('/gestion-administrateurs');
}
But I cannot update THIS user's type, this code changes ALL users' types lol, it's not what I wanted. Do you know with this code, how can I change THIS user's type ?
Thanks, I hope you'll understand my request ^^
you are selecting all the users by this query DB::table('users'),
assuming you are receiving id in request
you must select one row by adding a where condition DB::table('users')->where('id',$request->id)->update(['type' => $request->type])
You need to pass user ID as route part, or as request param
For example, you may create following route for updating users:
// Dont forget to protect this route with middleware like "can:edit-users"!
Route::post('/user/{id}', 'UserController#update');
then, render in template button to made user admin:
<form method="post" action="/user/{{ $user->id }}">
#csrf
<input type="hidden" name="type" value="admin">
<button type="submit">Make admin</button>
</form>
And create update method:
public function update(Request $request)
{
$request->validate([
'type' => 'required|exists:users',
]);
DB::table('users')
->where('id', $request->id)
->update(
['type' => $request->type]
);
return redirect('/somewhere');
}
Related
I am making a site for drawing in laravel and I don't know how to make a save button for my drawings,all I need to save for now are the name of the canvas and the size of it,one problem is that the name is stored in an input and I don't know how to access it,the other what do I return after saving it
<a href="{{route('canvas.save',['size' =>$size])}}">
This is how I transfer the size,but the name I don't know yet how to transfer
this is the input where I store it
<input oninput="ChangeInput(this.value)" value="Canvas" type="text" name="title" id="title">
this is how I add the data to the table
public function createDrawing($name,$size,$id){
return Drawing::create([
'name' => $name, //the name of the canvas
'canvas_size' => $size,
'users_id' => $id //this is a foreign key
]);
}
the structure of the route is
Route::get('canvasSave/{size}',[CustomAuthController::class,'SaveDrawing'])->name('canvas.save');
public function SaveDrawing($size){
$check = $this->createDrawing(...,$size,1);
//how do I get the name here from the input
}
What do I return after creating the drawing was stored in the table,my idea was to return a Partial view like a Popup but still don't know how to do it,
I just dont understand how to save it via routes and I'm confused,your help would help a lot
So I managed to do the saving like this in the controller
public function createDrawing(array $data){
return Drawing::create([
'name' => $data['title'],
'canvas_size' => $data['size'],
'users_id' => $data['users_id']
]);
}
public function SaveDrawing(Request $request){
$data = $request->all();
$data['users_id'] = Auth::id();
$check = $this->createDrawing($data);
return View('main.introduction');
}
I did the route into the post like you said and things got clearer after I made the html in form
route:
Route::post('canvasSave',[CustomAuthController::class,'SaveDrawing'])->name('canvas.save');
HTML:
<form action="{{route('canvas.save')}}" method="POST">
#csrf
<input oninput="ChangeInput(this.value)" value="Canvas" type="text" name="title" id="title">
<input type="hidden" name="size" value="{{$size}}">
<button type="submit">Save</button>
</form>
after the save it just returns back to the main page
Use Route::post and pass all the data as a payload (body) on the request. Τhe easiest way is to add them in a form and the size can be a hidden input with the value or use a javascript ajax method to pass them as you like.
Still new to laravel, learning how the $request interacts with create.
here is my form for two of my variables for context:
<form method="POST" id="postForm">
{{-- #csrf --}}
<input type="hidden" id="id_hidden" name="id" />
<div class="form-group">
<label for="title"> Title <span class="text-danger">*</span></label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="category_description"> Description <span class="text-danger">*</span></label>
<textarea name="category_description" id="category_description" class="form-control"></textarea>
</div>
</form>
controller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'category_description' => 'required',
]);
$post = HmsBbrCategory::create($request->all());
if(!is_null($post)) {
return response()->json(["status" => "success", "message" => "Success! post created.", "data" => $post]);
}
else {
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
}
model:
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_id", "title", "category_description", "category_description_2"
];
my title and category_description is inserting fine with an auto incremented id column. What I am trying to do is just to add 2 columns: category_id and category_description_2 that just copies the value inserted by id and category_description
Question:
how does 'required' retrieve the data from the form? I would like to have the same data thats taken and adding it to my two new columns. I am aware that I cannot just simple add 'category_description_2' => 'required',because this won't get an existing data.
so basically
$id = id
$category_id = id
$title = title
$category_description = category_description
$category_description_2 = category_description
1
Here is my table for reference. This form was given to me and I want to understand to know more about Laravel, thanks for reading and I hope I can get some suggestions on what to add.
You are running ->validate([]) on the $request variable which takes all of the information that is laravel puts together during the post request. If you do
dd($request->all()); you will be able to see all of the data that is passed from the form that you can run different validate rules on.
If you would like to add other data into your $request variable in order to save it to your model, you can always just add it to the $request array like so: $request['variable_1'] = 'data for variable one' and so on
Since I see that you have category_id that you would like to reference in your saved record, I would suggest you create a relation in your HmsBbrCategory model and the parent model that category_id belongs to. This will help you keep the integrity of your database in tact.
As another option, you can structure your url in such a way that passes the category_id to your store method in the controller. You will then need to find that category id and make sure it exists and save it via the relation that you created:
public function store (Request $request, $category_id){
$main_category = Category:find($category_id); //make sure it exists
$new_record = $main_category->exampleRelation()->save($request->all());
if(!$new_record){
return failed save
}
return successful save message
}
By doing the above, it will automatically insert the category_id into your saved record.
As another alternative, you could create a hidden field in your form that references category_id and other fields that you would like to add to your record on save. However, keep in mind which "sensitive" information you would like the users to see if someone decide to view source on the browser window.
I have situation where an admin edits an employee form: The first name, last name, and SSN are required on ADDING an employee. No problems there. Where I have an issue is when EDITING the form. I have no problem validating the SSN as it is a unique field.
'ssn_edit' => 'required|unique:employees,ssn,' . $id
But what I DO have an issue with is the non-unique fields. I don't know how to set the validation to skip by ID when the field is NOT unique. Here is the entire rules section of the FormRequest:
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|unique:employees,ssn,' . $id
];
}
Obviously - this throws the validation error on first_name and last_name regardless if the field is populated or not.
Any help some of you Laravel gurus can throw my way would be GREATLY appreciated!
There is so many tricks you can do to solve the problem. But I only got two ways..
The first is: Prevent to send your ssn_edit value when you want to edit the employee
example:
<input type="text" value="{{ isset($employee) ? $employee->ssn_edit : old('ssn_edit') }}" #isset($employee) disabled #endisset name="ssn_edit">
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|sometimes|unique:employees,ssn,' . $id
];
}
The second is: Check your method before validate the employee.. is it POST or PUT, if it's PUT don't add the unique rule in your validation.
Conclusion: The validation will work every time you call the validation, no matter if you edit or add new employee. #CMIIW
You mustn't have error with validating non-unique fields, probably you have wrong edit form, set value attribute to input like
<input type="text" value="{{ $employee->first_name }}" name="first_name">
I'm new on Laravel and as I'm playing around with it I encounter this issue.
I have a registration system which worked fine but now I wanted to add a new field in my table (description field for users).
However, this description field, I don't want to be filled when the user signs up, I want the user to fill this when he gets on his profile and updates a modal window.
The problem is, if I let that filed empty, I get an error when I sign up saying that the description filed can't be empty.
This is what I use in my UserController in order to update the description field but I'm not sure if is correct.
public function postDesc(Request $request){
$this->validate($request, [
'description' => 'required|min:20'
]);
$user = User::all();
$user->description = $request->input('description');
$user->save();
return redirect()->route('user.profile.edit');
}
This is how I opened the form:
{!! Form::open(['method' => 'PUT', 'action' => 'UserController#postDesc', 'class' => 'profile-form']) !!}
You use required validation rule, that's why you get the message. You should use different validation rules for register page and profile update form.
Good practice is to create two Request classes and use them for validation of two forms.
In this scenario, I will prefer to keep your description column nullalbe(). So it won't throw an error that description field is empty at the time of sign up.
And later you can update the description field.
public function postDesc(Request $request)
{
$this->validate($request, [
'description' => 'required|min:20'
]);
// Get the logged in user id using auth and then updating description filed
$user = User::where('user_id', Auth::id())
->update([
'description' => $request->description
]);
return redirect()->route('user.profile.edit');
}
Always when the validation fails, I get a MethodNotAllowedHttpException
routes.php
Route::post('download', 'UrlController#download');
Route::post('search', 'UrlController#search');
UrlController.php
public function download(DownloadRequest $request)
{
dd($request->all());
}
DownloadRequest.php
public function authorize()
{
return true;
}
public function rules()
{
return [
'format' => 'required|between:1,13'
];
}
name.blade.php
{!! Form::open(['url' => 'download']) !!}
{!! Form::select('format', [
'Please select format',
'FormatGrp1' => [1 => 'best', 'p1','p2', 'p3', 'p4'],
'FormatGrp2' => [6 => 'p5', 'p6']
]) !!}
When "Please select format" is chosen and the form is submitted, I always get this error because "Please select format" has value 0 and i specified values must be between 1 and 13. (Look at DownloadRequest.php)
Thanks for help!
The error didn't come from the validation.
It was because it called the URL to go back and display the errors. And this is the search method.
So cause of the logic in search method the exception has been thrown.
When you have this error, in your if ($validator->fails()) { } consider that you are going to open the view you are working on for the first time, and add ->withErrors($validator)
For example:
public function edit($id)
{
$exams = Exam::all();
return view('exams.index', compact("exams"));
}
...
public function update(Request $request,$id)
{
$validator = Validator::make($request->all(),[
'start' => 'required',
'end' => 'required|after:start'
]);
if ($validator->fails())
{
$exams = Exam::all();
return view('exams.index', compact("exams"))->withErrors($validator);
}
//Your update code if validator not fails
}
I didn't exactly understand what this user was trying to explain as the actual problem or solution - I came across this question as I had the same issue and thought I would describe what I had done in error and how I solved it...
For me, I was building a site where users would submit photos. When the user clicked on the "add photo" it took them to a page where they had to check a box to accept a legal disclaimer. This form with the checkbox was a POST request. After they accepted it they would get re-directed to the photo submission page... WHICH WAS ALSO A FORM WITH A POST REQUEST. This was my issue: back to back POST request pages. If the user entered invalid data on the submission form, or didn't enter data in a field at all Laravel tries to essentially hit the "back button" in your browser and keep the form filled with the data the user did enter. The problem is that the "back" button (or the way the user came to this page) was from a POST request, so it couldn't do it. It gave me the error described above. Once I switched the legal acceptance page to a GET request form and updated the route to match everything started working fine. It was a foolish error on my part, I just hope to mitigate this frustration for others as they are learning to develop in Laravel. Have a great day!