Laravel blade checkbox is always invalidated - php

I'm using laravel 9. When I check a checkbox and save it, I always get the error The calculator field must be true or false.
Route::get('/', function () {
return view('welcome');
});
Route::post('save', function(Request $request) {
$request->validate([
'calculator' => 'required|boolean'
]);
return redirect('/');
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
#if($errors->any())
<div class='alert alert-danger rounded-0 mb-0'>
{!! implode('<hr />', $errors->all(':message')) !!}
</div>
#endif
<form method="post" action="save">
#csrf
<div>
<input type="checkbox" class="form-control" name="calculator" id="calculator" />
<label for="calculator">Calculator</label>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>

That's because Laravel sends checkbox value as on
You can see that if you dump your request:
dd($request->input());
In order to bypass that, you can add a value to your checkbox:
<input type="checkbox" class="form-control" value="1" name="calculator" id="calculator" />
This way, Laravel will now send 1 as your input, and you will be able to validate it with boolean rule.
Also, you can use a different approach. Laravel provides accepted rule as well:
The field under validation must be yes, on, 1, or true. This is useful for validating "Terms of Service" acceptance.
So in this case, you would just change your validation rule:
$request->validate([
'calculator' => 'required|accepted'
]);

Related

laravel: routing error when sending validation error messages

I do not understand what is wrong with this code being at the address 127.0.0.1:8000/getIncomingTransfers I am trying to process a form by sending it to the address 127.0.0.1:8000/authenticateTransfer but I get the error The GET method is not supported for this route. Supported methods: POST.
in my web.php file
Route::name('reference')->post('getIncomingTransfers', [MainController::class, 'getIncomingTransfers']);
Route::name('security')->post('authenticateTransfer', [MainController::class, 'authenticateTransfer']);
in my getIncomingTransfers.blade.php file
<form action="{{ route('security') }}" method="post">
#csrf
<div class="form-group">
<input type="text" class="form-control {{ $errors->has('SecurityAnswer') ? 'error' : '' }}" name="SecurityAnswer" id="SecurityAnswer">
<button type="submit" name="send" class="btn btn-primary solid">Confirm</button>
</div>
<!-- Error -->
#if ($errors->has('SecurityAnswer'))
<div class="error" style="text-align: center; color: brown">
{{ $errors->first('SecurityAnswer') }}
</div>
#endif
</form>
in my MainController#authenticateTransfer file
public function authenticateTransfer(Request $request)
{
$this->validate($request, [
'SecurityAnswer' => 'required',
]);
return $request;
}
when I click on the submit button of the form with the SecurityAnswer field not empty there is no error but when the validation fails and the message of the validation error must be returned that's where I have this error. how can i solve the problem?.
I also want to specify that the getIncomingTransfers route is in POST by which a form is received to be processed before returning the view getIncomingTransfers.blade.php

Laravel beginner need help solving error 419

I'm currently working on my first web project with Laravel. The app will has a very simple task, the user puts in a date and my website will check if that date is in a set timeframe.
So its first getting user input, secound check if the input date is in between 2 other dates and last print a massage out on the view when depending on the outcome of step 2.
Sadly every time i press the submit-button which should give me some output i always get an 419 error, I hope someone can tell me what I am doing wrong.
Here is my view named welcome.blade.php
<!DOCTYPE html>
<html>
<body>
<b> Klausuretermin auswählen
</b>
<br>
<form method="POST" action="/dateCalc">
<input type="date" id="date" value="date">
<br>
<input type="text" name="klausurname" value="klausurname">
<br>
<button type="submit" name="submit">Submit</button>
</form>
<br>
#if (isset($result))
<p>{{ $result }}</p>
#endif
</body>
</html>
Here is my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DateCalc extends Model
{
public function checkDateBetween( $toCheck){
//still needs logic want to print out input to test the rest
return $toCheck;
}
}
here my controller:
<?php
namespace App\Http\Controllers;
use App\DataCalc;
use Illuminate\View\View;
use Illuminate\Http\Request;
class DateController extends Controller
{
public function index(): View{
return view('welcome');
}
public function checkDate(DateCalc $dateCalc): View{
$date = "OK";
return view('welcome', ['result' => $$date]);
}
}
and at last my routes:
Route::get('/dateCalc','DateController#index');
Route::post('/dateCalc', 'DateController#checkDate');
you have to add csrf protection in your form
<!DOCTYPE html>
<html>
<body>
<b> Klausuretermin auswählen
</b>
<br>
<form method="POST" action="/dateCalc">
#csrf
<input type="date" id="date" value="date">
<br>
<input type="text" name="klausurname" value="klausurname">
<br>
<button type="submit" name="submit">Submit</button>
</form>
<br>
#if (isset($result))
<p>{{ $result }}</p>
#endif
</body>
you can read more in documentation https://laravel.com/docs/9.x/csrf#main-content
Please add #csrf token in your form.
Example :
<form method="POST">
#csrf // CSRF
</form>

Parameter goes into array as the name of the field instead of the value

What am I trying to achieve?
I have "tasks" and each task can have multiple "notes", so when you select a Task and click notes, it takes you to a page with all the notes for the task in which you clicked.
Each note has a field called "task_id", so my problem is passing this task_id to the note.
I'm trying to pass it like this on the notes form:
<form method="POST" action="{{route('notes.store',$task)}}">
#include('notes.form')
</form>
And it goes into my controller
public function store(Request $r)
{
$validatedData = $r->validate([
'note' => 'required',
]);
$r['created_by'] = Auth::user()->user_id;
return $r;
/*
$note = Note::create($r->all());
return redirect('/notes')->with('store');
*/
}
But I return it to see how its going and I get this:
{"_token":"OmGrbYeQDl35oRnmewrVraCT0SHMC16wE4gD56nl","note":"363","created_by":4,"8":null}
That 8 at the end is actually the correct task id, but it appears as the name instead of the value.
What may be causing this?
This is my form view:
#csrf
<div class="col">
<div class="form-group">
<input type="text" class="form-control" name="note">
</div>
</div>
<div class="col-10">
<div class="form-group">
<button class="btn btn-success" type="submit">Add note</button>
<br><br>
</div>
</div>
These are my routes:
Route::get('/tasks/{task}/notes', ['as' => 'tasks.notes', 'uses' => 'NoteController#index']);
Route::get('/projects/{project}/tasks', ['as' => 'projects.tasks', 'uses' => 'ProjectController#seeTasks']);
Route::get('/projects/results','ProjectController#filter');
Route::get('/tasks/results','TaskController#filter');
Route::resource('projects','ProjectController');
Route::resource('clients','ClientController');
Route::resource('tasks','TaskController');
Route::resource('users','UserController');
Route::resource('notes','NoteController');
You are trying to pass the task_id as a route parameter, but your notes.store route has no route parameters.
Verb Path Action Route Name
POST /notes store notes.store
Adding the task_id as a hidden input should properly send it with the request:
<form method="POST" action="{{ route('notes.store') }}">
<input type="hidden" name="task_id" value="{{ $task->id }}">
#include('notes.form')
</form>

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

Display different errors based on which submit button has been clicked in Laravel 5.1

I hope you're all doing well and having a good festive season. I wanted to post a question to find out how I can display the errors for a particular form in Laravel 5.1 based on what submit button has been clicked. Here is some code to give a better explanation of what I'm trying to do.
<form action="{{ url( '/auth/login' ) }}" id="login" method="post">
#if (count($errors) > 0)
<div class="show validation-summary">
... display error container only when the login submit button has been clicked
</div>
#endif
<input name="submit" type="submit" value="Login" />
</form>
<form action="{{ url( '/auth/register' ) }}" id="register" method="post">
#if (count($errors) > 0)
<div class="show validation-summary">
... display error container only when the register submit button has been clicked
</div>
#endif
<input name="submit" type="submit" value="Register" />
</form>
Currently both validation divs are displaying when clicking the Login or Register submit buttons, but I only want to display the validation div which relates to that form that was submitted.
You can use a named error bag.
For example, in your controller you can do:
$validator = Validator::make(Input::all(), [
'some_input' => 'required',
], [
'some_input.required' => 'The input is required.',
]);
// ...some other code may go here
if($validator->fails())
{
return redirect()
->back()
->withInput()
->withErrors($validator, 'named_error_bag');
}
To display the errors in your named error bag in the view you can do.
#if(!empty($errors->named_error_bag->first('error_name')))
{{ $errors->named_error_bag->first('error_name') }}
#endif

Categories