How handle this validation context? - laravel

I have below a form for a user enter some info to do a registration in a congress.
In the form below there is this part:
#foreach($selectedRtype['questions'] as $customQuestion)
<div class="form-group">
<label for="participant_question">{{$customQuestion->question}}</label>
<input type="text" #if($customQuestion->required == "1") required #endif class="form-control" name="participant_question[]" value="">
</div>
#endforeach
That code shows for each ticket type the custom questions associated with that ticket type. And adds the "required" attribute if in the ticket_type_questions table the required field is "1".
My doubt is how to validate in the RegistrationController storeRegistrationInfo(), because the field might be required or not, it depends of wether is "1" or "0" in the column "required" of the ticket_type_questions table. Do you know how to handle this context?
public function storeRegistrationInfo(Request $request, $id, $slug = null, Validator $validator){
$validator = Validator::make($request->all(),[
'name' => 'required|max:255|string',
'surname' => 'required|max:255|string',
'email' => 'required|max:255|string',
'participant_name.*' => 'required|max:255|string',
'participant_surname.*' => 'required|max:255|string',
'participant_question.*' => '?????'
]);
...
}
Table relationships relevans for the question:
1 to many between congress and ticket types (a congress can have many ticket types)
1 to many between ticket types and ticket_type_questions (a ticket type can have many custom questions)
1 to many between questions and ticket_type_questions (a question can be associated with many ticket types)
Example of the ticket_type_questions table:
id ticket_type_id question_id required
1 2 3 1 (means the ticket type with id 2 has the custom question 3 and is a required field)
// registration form
<form method="post" action="">
{{csrf_field()}}
<div class="form-group font-size-sm">
<label for="name" class="text-gray">Name</label>
<input type="text" required class="form-control" id="name"
name="name" value="{{ (\Auth::check()) ? Auth::user()->name : old('name')}}">
</div>
<div class="form-group font-size-sm">
<label for="surname" class="text-gray">Surname</label>
<input type="text" id="surname" required class="form-control" name="surname" value="{{ (\Auth::check()) ? Auth::user()->surname : old('surname')}}">
</div>
<!-- other form fields -->
<!-- if the all_participants is 1 in the confernece table it should appear for each selected ticket a section for the user
that is doing the registration insert the name and surname of each paarticipant -->
#if (!empty($all_participants))
#if($all_participants == 1)
#foreach($selectedTypes as $k=>$selectedType)
#foreach(range(1, $selectedType['quantity']) as $test)
<h6>Participant - 1 - {{$k}}</h6> <!-- $k shows the ticket type name -->
<div class="form-group font-size-sm">
<label for="participant_name" class="text-gray">Name</label>
<input type="text" name="participant_name[]" required class="form-control" value="">
</div>
<div class="form-group font-size-sm">
<label for="participant_surname" class="text-gray">Surname</label>
<input type="text" required class="form-control" name="participant_surname[]" value="">
</div>
#foreach($selectedType['questions'] as $customQuestion)
<div class="form-group">
<label for="participant_question">{{$customQuestion->question}}</label>
<input type="text" required class="form-control" name="participant_question[]" value="">
</div>
#endforeach
#endforeach
#endif
#endif
<input type="submit" href="#" value="Next"/>
</form>

You could create a Request class using following artisan command php artisan make:request RegisterRequest there you could give the column the property to be nullable, which means that the user does not need to check that specific input.
The Request Class would look something like this, its basically a validation class:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'nullable',
];
}
}
In this example the user does not have to fill the field email.
Further you just replace your Request class in your controller function parameter like this:
public function sent(RegisterRequest $request)
{
$data = $request->all();
....
}
And of course you have to import / use it properly like this:
use App\Http\Requests\RegisterRequest;

Related

Laravel : How to create custom Register

I have 2 register and login form. The one is used to user and others is used to admin role.
In user role, I using from laravel authentication, is good and work well.
But, the problem is when I create custom register from admin role, its can't work well.
It can't store to database, when I check using echo function, it's not print anything just refresh the page.
Could you help me, what is wrong ???
this is my route
Route::get('/adminregister', 'Auth\LoginController#formreg')->name('admin-reg');
this is my controller
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AregisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
// $this->middleware('guest');
}
public function create(Request $request)
{
$this->validate(request(),[
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
if ($request('confirmpassword') == $request('password')){
$user = User::create(request(['name','email' ,'password','is_admin' => True, ]));
// return redirect()->route('admin-login')->with('status', 'Successfully create account');;
}
else {
return redirect()->route('admin-reg')->with('status', 'Confirm Password not match');;
}
}
}
In this controller, fisrt I want to check the password will confirmation password then store it to database.
this is my view page
<form action ="{{ route('user-create') }}" method="POST" enctype="multipart/form-data" >
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="row mb-3">
<div class="col-md-12">
<div class="form-floating mb-2 mb-md-0">
<input class="form-control" id="inputFirstName" type="text" placeholder="Enter your first name" name="name" />
<label for="inputFirstName">Name </label>
</div>
</div>
</div>
<div class="form-floating mb-3">
<input class="form-control" id="inputEmail" type="email" placeholder="name#example.com" name="email"/>
<label for="inputEmail">Email address</label>
</div>
<div class="row mb-3">
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPassword" type="password" placeholder="Create a password" name="password" />
<label for="inputPassword">Password</label>
</div>
</div>
<div class="col-md-6">
<div class="form-floating mb-3 mb-md-0">
<input class="form-control" id="inputPasswordConfirm" type="password" placeholder="Confirm password" name="confirmpassword" />
<label for="inputPasswordConfirm">Confirm Password</label>
</div>
</div>
</div>
<div class="mt-4 mb-0">
<div class="d-grid"><button type="submit" class="btn btn-primary">Create account</button></div>
</div>
</form>
Do you have any suggestion of how to fix it? It cant store anything in database, and when I check it using " echo " there is nothing :)
Thank you
The confirmed rule is looking for a field name {field}_confirmation. So if you are trying to confirm the 'password' input it would be looking for a field named password_confirmation. So that input in the form needs to be changed to the name password_confirmation.
You won't need to compare the 2 password fields that are submitted since the confirmed rule has done that for you already (that is what it is for; to confirm that they match).
The Request class is not callable, $request(...). That will throw an error since it isn't callable (there is no __invoke method defined on it to make it callable).
To create the User you can get the fields you need easily with the only method:
$request->only('name', 'email', 'password')
You can add your is_admin value to the array returned from the only call:
User::create($request->only('name', 'email', 'password') + ['is_admin' => true])
You will have to make sure that the is_admin field is "fillable" on the Model.
In general you don't need to be calling request() any where in this method since you have a Request instance injected as $request already.
Also, your form isn't handling a file upload so you don't need enctype="multipart/form-data".

How to return inputs in Laravel 8 (rows) after failed validation

Im using Laravel8, and I want to return the inputs after failed validation in the form.
**VIEW:
<div class="form-group">
<label>{{__("Coupon Code")}} <span class="text-danger">*</span></label>
<input type="text" maxlength="50" required value="{{$row->code}}" placeholder="{{__("Unique Code")}}" name="code" class="form-control">
Controller:
public function store( Request $request,$id ){
$request->validate([
'code'=>[
'required',
'max:50',
'string',
'alpha_dash',
Rule::unique('bravo_coupons')->ignore($id > 0 ? $id : false)
],
'amount'=>['required'],
]);
Thanks
You can use old() helper function like so:
<input value="{{ old('code') }}">

contact form become doesn't work and won't show error message

I made Laravel contact form project a year ago and it worked perfectly. I haven't use it. And today I put same this project at rental web server(same server and same plan)but it doesn't work. and It won't show any error message.
First problem is about validation.
At my local(I use XAMPP)I can go next page which is confirm.blade.php. however I deploy at my real server and I fill up all info at text field and click submit. but the page refreshing really quick and doesn't go next page which is confirm.blade.php. Could someone gime me a direction please?
Laravel Framework is 5.7.28
UPDATE
FORM CODE
#extends('layouts.default_mail')
#section('title', 'test')
#section('content')
<form class="form-horizontal" role="form" method="post" action="{{url('/mail')}}">
<input type="hidden" name="_token" value="{{csrf_token()}}">{{-- CSRF対策--}}
<!--↓↓件名↓↓-->
<div class="form-group">
<label for="name" class="control-label col-sm-2">Name</label>
<div class="col-sm-10 #if($errors->has('name')) has-error #endif">
<input type="text" name="name" id="title" value="{{ old('name') }}" class="form-control" placeholder="" autofocus>
#if($errors->has('name'))
<p class="text-danger" style="margin-bottom: 30px;">{{ $errors->first('name') }}</p>
#endif
<!--/.col-sm-10--></div>
<!--/.form-group--></div>
<!--↑↑件名↑↑-->
<!--↓↓メールアドレス↓↓-->
<div class="form-group">
<label for="email" class="control-label col-sm-2">Email:</label>
<div class="col-sm-10 #if($errors->has('email')) has-error #endif">
<input type="email" name="email" id="email" class="form-control" placeholder="Type Email address" value="{{ old('email') }}" autofocus>
#if($errors->has('email'))
<p class="text-danger" style="margin-bottom: 30px;">{{ $errors->first('email') }}</p>
#endif
<!--/.col-sm-10--></div>
<!--/.form-group--></div>
<!--↑↑メールアドレス↑↑-->
<!--↓↓本文↓↓-->
<div class="form-group">
<label for="body" class="control-label col-sm-2">body</label>
<div class="col-sm-10 #if($errors->has('body')) has-error #endif">
<textarea class="form-control" name="body" id="body" rows="3" placeholder="messages" autofocus>{{ old('body') }}</textarea>
<!--/.col-sm-10--></div>
<!--/.form-group--></div>
<!--↑↑本文↑↑-->
<!--↓↓time and order number ↓↓-->
<input type="hidden" name="sno" class="form-control" value="{{ date('YmdHis') }}">
<input type="hidden" name="time" class="form-control" value="{{ date('Y-m-d H:i:s') }}">
<!--↑↑time and order number ↑↑-->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary btn-block">submit</button>
</div>
<!--/form-group--></div>
</form>
#endsection
Is this deploy and routing problem? but it worked a year ago and I didn't change any code...I update head of 1st page which is index.blade.php
<form class="form-horizontal" role="form" method="post" action="{{url('/mail')}}">
and here is .env file
APP_URL=http://localhost
Everyone. Thank you.
<?php
namespace App\Http\Controllers;
use Mail;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Contact;
class MailController extends Controller
{
public function index(){
return view('mail.index');
}
public function confirm(Request $request)
{
$rules = [
'name' => 'required',
'hp' => 'required',
'email' => 'required|email'
];
$this->validate($request, $rules);
$data = $request->all();
// setting session key value for you data
$request->session()->put('data',$data);
// DEBUG
Log::debug('$data="'.$data.'"');
Log::debug('$request="'.$request.'"');
return view('mail.confirm', compact("data"));
}
/*
* complete page
*/
public function complete(Request $request)
{
$data = $request->session()->pull('data');
$token = array_shift($data);
$Contact = Contact::create($data);
Mail::send(['text' => 'mail.temp'], $data, function($message) use($data){
$message->to($data["email"])->bcc('11223344#yahoo.co.jp')->from('2233#sunshine.online')->subject('Thank you。');});
Mail::send(['text' => 'mail.admintemp'], $data, function($message) use($data){
$message->to('2233#sunshine.online')->from('1122#sunshine.online')->subject('u got mail');});
$data = session()->regenerateToken();
return view('mail.complete');
}
}
Here is table info
CREATE TABLE `contact` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(100) NOT NULL,
`hp` varchar(100) NOT NULL,
`email` varchar(250) NOT NULL,
`sec` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`body` varchar(100) NOT NULL,
`sno` int(10) NOT NULL,
`time` timestamp NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
And here is model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use EncryptsAttributes;
protected $encrypts = [
'name',
'hp',
'email',
'body'
];
protected $fillable = [
'name',
'title',
'sec',
'hp',
'email',
'body'];
}
Change This:
$this->validate($request, $rules);
To:
request()->validate($rules);
I think this will help you.
$request->validate([
'name' => 'required',
'hp' => 'required',
'email' => 'required|email'
]);

Laravel Form Request validation issues

I'm attempting to create a single error response message for array input:
This is my form:
<div class="form-group col-md-12">
<div class="row">
<div class="col-md-6">
<label for="client-type">Client Type</label>
<input type="text" name="client_type[]" class="form-control" value="Panelist" readonly>
</div>
<div class="col-md-6">
<label for="commission-percentage">Commission Percentage</label>
<input type="number" name="commission_percentage[]" class="form-control">
</div>
</div><br>
<div class="row">
<div class="col-md-6">
<label for="client-type">Client Type</label>
<input type="text" name="client_type[]" class="form-control" value="Non Panelist" readonly>
</div>
<div class="col-md-6">
<label for="commission-percentage">Commission Percentage</label>
<input type="number" name="commission_percentage[]" class="form-control">
</div>
</div>
Here's my controller:
public function store(StoreCommissionsList $request)
{
$attributes = $request->validated();
dd($attributes);
}
And finally my StoreCommissionsList form request:
public function rules()
{
$commission = request('commission_percentage');
$rules = [];
$rules['role_id'] = 'required';
$rules['client_type'] = 'required';
if ( $commission[0] == null && $commission[1] == null )
{
$rules['commission_percentage'] = 'required';
}
return $rules;
}
public function messages()
{
return [
'role_id.required' => 'Please select a user role',
'client_type.required' => 'Please input a client type',
'commission_percentage.required' => 'Please fill in a percentage commission for each client type',
];
}
What is happening is: If all the fields in my form are blank, only the role_id seems to be passing the validation check in terms of returning the required validation message. The commission_percentage is not validated at all and after inputting role_id, the form submits meaning the commission_percentage validation is overlooked for some reason.
Kindly assist.
Update
Here's my implementation using the wildcard (*) dot-notation.
public function rules()
{
$rules = [];
$rules['role_id'] = 'required';
$rules['client_type.*'] = 'required';
$rules['commission_percentage.*'] = 'required';
return $rules;
}
For this, the validation error messages will be duplicated for each array item in the request, in my case, something like this:
The commission_percentage.0 field is required.
The commission_percentage.1 field is required
So the earlier implementation in my rules was a possible solution for this duplicate issue.

How to insert (create) data (CRUD) FORM in blade in multiple languages into database and read it out with LARAVEL MULTILANGUAGE - LOCALIZE?

I have followed this tutorial (https://mydnic.be/post/how-to-build-an-efficient-and-seo-friendly-multilingual-architecture-for-your-laravel-application) about laravel multilanguage and localization. Everything seems ok, except I want to CREATE a CRUD for inserting this posts with title and content in multiple language - and STORE it in database - and then read it out in index blade.
Can you show me an example of CRUD in this way in blade for CREATE and in Controller for CREATE and STORE function. How to make this to work?
This is my simple main CRUD, how to extend this to be able to creating and storing into multiple language when creating.
And how to extend the controller for storing in multiple language when using this translatable package from tutorial above (link).
CRUD:
<form method="POST" action="/posts">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea id="content" name="content" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Publish</button>
</div>
</form>
CONTROLLER
public function store(Request $request)
{
$post = Post::all();
$this->validate(request(), [
'title' => 'required',
'content' => 'required'
]);
$post = new Post;
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect('/');
THANKS :)
I'm the author of the tutorial.
The whole point of that implementation is that you don't have to worry about the model locale at all. The locale is set through the URL "/en/..."
So if you make a POST request to your model store URL like so :
POST /en/post {payload}
The App Locale of your laravel application will be automatically set before you even reach the PostController#store method.
Then, you can simply create your model like you would usually do (like in your exemple, that's correct) , and the model will be stored with the according locale.
Now that your model is initially created with the defined locale, you should be able to edit it in another language.
So you can go to this URL: /en/post/:id/edit then switch to another locale : /fr/post/:id/edit and you will notice that all input of the translatable fields are blank. That's normal because the 'fr' translation of that model doesn't exist yet.
You can thus fill the form with the 'fr' translated field, then save (update the model). And the translation will be saved. Your model is now translated :)
Hope this helps !
PS you can have a look at the example code here https://github.com/mydnic/Laravel-Multilingual-SEO-Example
So based on the tutorial, you'll have a column in your posts table called locale
Then in your view, you can add a select field from which you can chose the locale
<div class="form-group">
<label for="locale">Locale</label>
<select id="locale" name="locale" class="form-control">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</div>
Then in your controller add the following line:
$post->locale = $request->locale;
Put locale in your $fillable array within the post model.
THIS IS WORKING WELL IN THIS SITUATION:
CONTROLLER:
public function create()
{
return view('services.new');
}
public function store(Request $request)
{
$service = new Service();
$service->save();
$this->validate($request, [
'title2' => 'required|max:350',
'content2' => 'required'
]);
foreach (['en', 'bs'] as $locale) {
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
}
$service->translateOrNew('en')->title = $request->title;
$service->translateOrNew('en')->content = $request->content;
$service->translateOrNew('bs')->title = $request->title2;
$service->translateOrNew('bs')->content = $request->content2;
// $article->translateOrNew('en')->text = ['texten'];
// $article->translateOrNew('ka')->name = ['nameka'];
// $article->translateOrNew('ka')->text = ['textka'];
// return $article;
// exit();
$service->save();
return redirect()->back();
}
BLADE FOR CREATE + CSS (in background):
<form action="{{route('service.store')}}" method="POST">
{{csrf_field()}}
<div class="tabset">
<!-- Tab 1 -->
<input type="radio" name="tabset" class="radio1" id="tab1" aria-controls="marzen" checked>
<label for="tab1">Bosanski</label>
<!-- Tab 2 -->
<input type="radio" class="radio1" name="tabset" id="tab2" aria-controls="rauchbier">
<label for="tab2">Engleski</label>
{{-- <!-- Tab 3 -->
<input type="radio" name="tabset" id="tab3" aria-controls="dunkles">
<label for="tab3">Dunkles Bock</label> --}}
<div class="tab-panels">
<section id="marzen" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Naslov*(bs)</lebal>
<input type="text" class="form-control" name="title2">
</div>
<div class="form-group">
<lebal>Opis*(bs)</lebal>
<textarea class="form-control" name="content2"></textarea>
</div>
</section>
<section id="rauchbier" class="tab-panel">
<h2>Dodaj novu uslugu</h2>
<div class="form-group">
<lebal>Title (EN)</lebal>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<lebal>Description (EN)</lebal>
<textarea class="form-control" name="content"></textarea>
</div>
</section>
<section id="dunkles" class="tab-panel">
<h2>Tab3</h2>
</section>
</div>
<input type="submit" value="Submit">
</form>
WEB.PHP:
Route::post('/create',[
'uses' => 'ServicesController#store',
'as' => 'service.store'
]);

Resources