How to store saved checkbox value in Laravel? - laravel

I'm studying Laravel and made contact form.
my Laravel Framework is 7.15.0
I wrote this code to saving form values useing old function.
<input class="form-check-input" type="radio" name="q1[]"
value="A" #if(is_array(old('q1')) && in_array("A", old('q1'))) checked #endif>
<label class="form-check-label" >A</label>
<input class="form-check-input" type="radio" name="q1[]"
value="B" #if(is_array(old('q1')) && in_array("B", old('q1'))) checked #endif>
<label class="form-check-label" >B</label>
However after I wrote this I couldn't store data to my mysql.
Here is error message.
ErrorException
Array to string conversion
vendor/laravel/framework/src/Illuminate/Support/Str.php:449
Seems like saving array data to my mysql is problem I guess.
Here is my controller code.
Could someone teach me how to write store data as not array please?
public function ContactUsForm(Request $request) {
// Form validation
$this->validate($request, [
'name' => 'required',
]);
Contact::create($request->all());
\Mail::send('mail', array(
'name' => $request->get('name'),
'q1_s' => $request->get('q1')
), function($message) use ($request){
$message->from($request->email);
$message->to('mail#myemailadress.com', 'you got mail ')->subject($request->get('you got mail'));
});

Related

Laravel request validation on array

Lets say I submit this form:
<form>
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
<input type="text" name="emails[]">
</form>
How do I then validate that at least one (anyone) of the $request->emails[] is filled?
I have tried this - however it does not work:
$request->validate([
'emails' => 'array|min:1',
'emails.*' => 'nullable|email',
]);
Laravel 7
Try this
$request->validate([
'emails' => 'array|required',
'emails.*' => 'email',
]);
Cordially
To meet your requirement, you may need custom rule
First create a rule, php artisan make:rule YourRuleName
inside YourRuleName.php
public function passes($attribute, $value)
{
foreach(request()->{$attribute} as $email) {
// if not null, then just return true.
// its assume in arrays some item have values
if ($email) { // use your own LOGIC here
return true;
}
}
return false;
}
Then,
$request->validate([
'emails' => [new YourRuleName],
]);

Laravel Form Request Validation error message bag contains empty value in view?

I have a Request file to validate the form. What I am encountering is that, I have at least 24 form fields to validate, but the problem is fields get validated and return back to the view, when validation fails. But the errors is not get sent to view.
But, I mentioned the rules for lets say only 6 fields, then the message is being displayed properly in the view.
I have done the research on stackoverflow, and tried every solutions, but none work for me.
use this type of dorm fields in your view
<div class="col-8 ml-auto">
<input id="serialNumber" type="text" class="form-control t-cap"
name="serialNumber" value="{{ $invoice->serialNumber }}">
</div>
#if ($errors->has('serialNumber'))
<span class="col-md-12 form-error-message">
<small for="serialNumber">{{ $errors->first('serialNumber') }}</small>
</span>
#endif
</div>
And in Your Controller use Like This
$rules = array(
'customer.mobile'=> 'required|regex:/\+91[[:space:]]\d{10}/',
'serialNumber' => 'required',
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return Response::json(array(
'status' => 0,
'errors' => $validator->errors()
), 400);
}

Laravel 5.6 Signed URL not valid after user submit form

In my system, using Laravel 5.6, we send a email with a invitation link (using signed URL) where the user click, fill a form and submit it to the server. In this point the user is saved.
The signed URL already contains data like email and perfil_id (like role_id) that will be assigned when the user submits the form.
At which point should I use the $request->hasValidSignature() method?
Because if I wait for the user to fill the form and submit, the method called here will give false to hasValidSignature(). If I validate when passing the view for the user to see the form, the validation will pass but before sending the form the user will be able to tamper with data.
Signed URL inside controller
$url = URL::temporarySignedRoute('completar', now()->addHours(5), [
'email' => $request->get('email'),
'perfil_id' => $request->get('perfil_id'),
'empresa_id' => auth()->user()->empresa_id,
]);
Mail::to($request->get('email'))->send(new UserRegistrationInvite($url));
Form inside the view that user has to fill after using the link on email
<form action="{{route("aceitar")}}" method="post">
<input type="hidden" name="email" value="{{$request['email']}}">
<input type="hidden" name="perfil_id" value="{{$request['perfil_id']}}">
<input type="hidden" name="empresa_id" value="{{$request['empresa_id']}}">
<input type="hidden" name="signature" value="{{$request['signature']}}">
<br>
<label for="name">Digite seu nome: </label>
<input type="text" id="Nome" name="name" placeholder="Nome">
<br>
<label for="password">Digite sua senha: </label>
<input type="password" name="password" id="password">
<br>
<label for="password_confirmation">confirme sua senha: </label>
<input type="password" name="password_confirmation" id="password_confirmation">
<hr>
<button type="submit" id="convite">Enviar</button>
</form>
function called when user submits form. here validation will fail
public function aceitar(Request $request) {
// verifica se a signed URL é válida
if (!$request->hasValidSignature()) {
abort(response()->json('URL não válida - aceitar', 403));
}
// ao submeter o formulario anterior, faz validação
$validator = Validator::make($request->all(), [
'name' => 'required',
'perfil_id' => 'required',
'empresa_id' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
// se validação falhar exibe erros na tela
if ($validator->fails()) {
return $validator->errors();
} else {
// se passar na validação usuário é criado com perfil e permissões ja relacionadas
$usuario = User::create([
'email' => $request->email,
'name' => $request->name,
'password' => bcrypt($request->password),
'empresa_id' => $request->empresa_id,
]);
$usuario->perfil()->attach($request->perfil_id);
return 'Usuário criado com sucesso';
}
thanks for your time.
The signature is only valid on the first URL that the user visits: 'completar'.
When they post the form, the same signature is no longer valid on the 'aceitar' route.
You can verify the signature before even showing them the form and consider it trusted.
You can also generate another temporary signed URL for the post route in the form if you want to add another validation step.

Get Model and id of the Model you are adding a note to

Basically,
I have a notes table with a polymorphic relationship with videos and users and want to determine how on my store method in my NotesController I get which model I am added a note to, and the id in that table. This is my create query on my store method
$note = Note::query()->create([
'body' => $request->get('body'),
'user_id' => \Auth::id(),
'noteable_id' => 1, **(needs to be dynamic)**
'noteable_type' => Video::class, **(needs to be dynamic)**
]);
Blade
<form action="{{route('admin.note.store'}}" method="post">
{{csrf_field()}}
<div class="input-group">
<input id="btn-input" name="body" required="true" type="text" class="form-control input-sm" placeholder="Type your message here...">
<span class="input-group-btn">
<button type="submit" class="btn btn-warning btn-sm" id="btn-chat">
Submit
</button>
</span>
</div>
</form>
Essentially I want to know how I can retrieve the noteable_type = (Model I'm updating) and the noteable_id (id of the record I'm adding a note to)
Is there any way of retrieving this dynamically on the request?
Thanks
You need to get the video or any other model some way. If your route contains the video id then you can use that in your controller. Here are some ways you can do this.
//Get your video model
$video = Video::find(...);
$note = \Auth::user()->create([
'body' => $request->get('body'),
'noteable_id' => $video->id,
'noteable_type' => get_class($video),
]);
// OR
$note = new Note([
'body' => $request->get('body'),
'user_id' => \Auth::id(),
]);
$video->note()->save($note);
Run php artisan route:list and post it so that i can advise you on how to fetch the model.

Laravel multiple delete checkbox?

I want to delete only checked tasks. At the moment I have this:
<form method="POST" action="/destroy">
#foreach($tasks as $t)
<label>
<input type="checkbox" name="checked[]" value="$t->id">
</label>
#endforeach
<button type="submit">Submit!</button>
</form>
This is my Controller
public function destroy(Request $request)
{
$this->validate($request, [
'checked' => 'required',
]);
$checked = $request->input('checked');
Task::destroy($checked);
}
And this is my route
Route::post('/destroy', [
'uses' => 'Controller#destroy',
]);
I don't get no error but the system does not work
I fixed the problem! Thanks for your support!
The problem was that my id variable was a hash.

Resources