Single Checkbox Form Laravel 5.5 - laravel

I'm working on a webpage where users can click a checkbox; any user can click the checkbox, and the result will be the same when viewed by all users. So, if User A checks the box, User B will see it as checked. If User B then unchecks it, User A will see it as unchecked.
I can get the checkbox to display the value from the database, but I can't seem to get the value to change and update in the database when a user clicks on the checkbox.
My blade layout looks like this:
<form method="POST" action="{{ action('QuestionController#answered', $question->id) }}" role="form">
{{ csrf_field() }}
<input type="checkbox" id="answered" name="answered" value="0" #if($question->answered == 1) checked #endif> Answered
</form>
The function in my controller looks like this:
public function answered(Request $request, $id)
{
$request->request->add(['answered_userid' => $this->userId]);
$this->validate($request, [
'answered' => 'required',
'answered_userid' => 'required'
]);
Question::find($id)->update($request->all());
}
}
And, in my routes file, I have this:
Route::post('questions/answered', ['as' => 'questions.answered', 'uses' => 'QuestionController#answered']);
EDIT: I've updated it to include the name, but I'm still running into the same problem.

You have to set a name in the input. The request will use the name of the input as the parameter:
<input type="checkbox" name="answered" id="answered" value="0" #if($question->answered == 1) checked #endif>

Set the name and its value
<input type="checkbox" name='answered' {{$question->answred ==1 ? Value="1" checked : value="0"}}>

Related

image does not want to be updated if the other values are not changed

I want to update the user image but the user image will only be updated if other values are also updated, such as name/username, I have tried various ways, even though in the edit post section there is no problem
so this is my form
<form action="/profile/{{ auth()->user()->id }}" method="post" enctype="multipart/form-data">
#method('put')
#csrf
<label for="">Name</label>
<input type="text" name="name" value="{{ auth()->user()->name }}">
<label for="">Username</label>
<input type="text" name="username" value="{{ auth()->user()->username }}">
<label for="">Profile Picture</label>
<input type="file" name="image">
<button type="submit">Update</button>
</form>
my web route
Route::get('/profile/{user}/edit', [ProfileController::class, 'edit'])->middleware('auth');
my ProfileController
$rules = [
'name' => ['required', 'max:15'],
'username' => ['required', 'min:5', 'max:12', 'unique:users'],
'image' => ['nullable','image','file','max:1024'],
];
$validatedData = $request->validate($rules);
if($request->file('image')) {
if($user->image){
Storage::delete($user->image);
}
$validatedData['image'] = $request->file('image')->store('profile-images');
}
$user->update($validatedData);
return back();
I have tried several ways and I have also created an edit post feature and it works well, I tried to copy and paste the code and change a little from the edit post feature but it doesn't work, the image is only updated if the other values are also edited / updated, what I want is that the image is updated even if the others are not updated, thank you
It seems to be due to the browser cache history.
Browsers usually store image data in cache. So if the image name is the same it won't be updated.
So I solved this problem like this.
All image names contain a unique random string with extension + ?
ex:Lynn.jpg?33f3r3

Post form in a button

In the admin dashboard you can make a post inactive if its active and vice versa. When you click on the button: 'make inactive', you send this form
<form method="POST" action="/admin/posts/inactivate/{{$post->id}}" enctype="multipart/form-data">
#csrf
#method('PATCH')
<input type="number" id="active" name="active" value="1" hidden readonly>
<button type="submit">Make inactive</button>
</form>
I dd'd and made sure the correct 'active' value is given but when I click the button to update the value in the database it just does nothing(redirects back to the dashboard with no change). I have this in my controller
public function makeInactive(Post $post){
$attribute = request()->validate([
'active' => 'required',
]);
$post->update($attribute);
return redirect()->back();
}
I have the same sort code for updating user data and it works just fine. Am I missing something?
it works for me :) but I made the "active" column in the database as integer what about yours ?

Edit Page takes me to "Page not Found" rather than "Update Route"

When i click on the Edit item Button on "Edit Page" the form submits and takes me to "Page Not Found" rather than update route..
Laravel
<form action="{{ route('admin.products.update', $id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
// else form elements goes here
</form>
//route file
Route::resource('/products','ProductController');
public function update(Request $request, Product $product)
{
return "hello";
}
i just wanted it to return "hello"
You need to pass the id parameter correctly in your route()
{{ route('products.update', [id => $id]) }}
Admin prefix is applied by the route, you don't need to pass it in route();

Error retrieving a checked Checkbox in Laravel as a boolean

I'm a bit new to laravel and I'm working on a laravel application which has a checkbox field which should have a boolean value of 1 when the user checks the checkbox, and 0 when the checkbox is unchecked.
I want to retrieve the boolean value as either 1 or 0 and save in a db.
Please assist?
View
<form method="POST" action="{{ route('b2c.getplans') }}" id="travel_form" accept-charset="UTF-8">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="check-now {{ $errors->has('spouse') ? ' has-error' : '' }}">
<h1 class="cover-travel">I am travelling with</h1>
<label class="spouse-me">
<h1 class="pumba">Spouse</h1>
<input id="spouse" type="checkbox" name="spouse">
<span class="checkmark" name="spouse"></span>
</label>
#if ($errors->has('spouse'))
<span class="help-block">
<strong>{{ $errors->first('spouse') }}</strong>
</span>
#endif
</div>
<button type="submit" class="form-b3c"> Get Plans</button>
</form>
Controller
public
function validatePlanEntries(Request $request)
{
$validation = $this->validate($request, [
'WithSpouse' => (\Input::has('spouse')) ? 1 : 0;
]
}
1st way is send correct value from frontend side
you can add jquery or javascript at frontend side on change event of checkbox :
<input type="checkbox" name="checkbox" id="myCheckbox" />
<script>
$(document).on('change','#myCheckbox',function(){
if($(this).is(':checked')){
$('#myCheckbox').val(1);
}else{
$('#myCheckbox').val(0);
}
});
</script>
at your backend side , now you can check :
$yourVariable=$request->input('checkbox');
2nd way is only check at your backend
you will get your checkbox value=on if it checked
if($request->input('checkbox')=='on'){
$yourVariable=1;
}else{
$yourVariable=0;
}
you can use ternary condition as well , like :
$yourVariable = $request->input('checkbox')=='on' ? 1:0;
You don't have to validate a checkbox value. because if its checked it sends the value of on, and if it's not checked it doesn't send anything.
So, all you need is that get whether the check box is checked or not, you can do as follow.
to retrieve the boolean value of the checkbox,
Controller
// since you haven't provide any codes in the controller what
// are you gonna do with this value,
// I will juts catch it to a variable.
$isChecked = $request->spouse == 'on'
To retrieve checkbox value from request as boolean:
$yourModel->with_spouse = (bool) $request->spouse;
If checkbox is checked then it's value (on by default) will be passed to request and casting non-empty string to boolean will give you true. If checkbox is not checked then spouse key won't be passed to request at all, so $request->spouse will return null. Casting null to boolean will result in false (in PHP true is int 1 and false is int 0, which is exactly what you want).

Laravel 5 Plain Html MethodNotAllowedHttpException

Hello so I am trying to make an update form in Laravel using plain html. The url of my edit form is http://localhost:8000/profile/sorxrob/edit, sorxrob is the username. And the code in that url is:
<form class="form-horizontal" role="form" action="" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="_method" type="hidden" value="PATCH">
//more inputs
</form>
And in my controller named AccountController:
public function update(Request $request, $id)
{
$account = Accounts::findOrFail($id);
$input = $request->all();
$account->fill($input)->save();
return 'success';
}
And I am getting the error MethodNotAllowedHttpException when I click the update button. Is it because my action is equal to nothing? If yes, what is the correct way of routing there?
This is due to your action url which is not correct routing url. Use the following
(1) First define a route in your route.php file
Route::post('profile/{username}/edit', array('as' => 'profile.update', 'uses' => 'AccountController#update'));
(2) Change your action attribute from your form tag
action="{{ URL::route('profile.update', [$username]) }}"
here $username variable will be passed from your AccountController#edit method.

Resources