There are space comes after every character of field name while displaying errors in blade template in laravel 9 as mentioned in uploaded image
my code is mentioned as below
CODE IN HTML IS :
<form action="{{route('saveAsset')}}" method="post">
{{#csrf_field()}}
<div class="form-group">
<label for="assetTitle" class="mt-2 mb-2">{{$assetCategory->category}} TITLE :</label>
<input type="text" class="form-control" name="assetTitle" id="assetTitle" placeholder="Enter Asset Title">
</div>
<div class="inputError">#error('assetTitle') Error: {{ $message }} #enderror </div>
<input type="hidden" name="assetCateId" id="assetCateId" value="{{$assetCategory->id}}">
#if(count($attributes) > 0)
#foreach($attributes as $attribute)
<label for="assetType-{{$attribute->attr_id}}" class="mt-4 mb-2">{{$attribute->attr_title}} : </label>
<div class="form-group">
<select class="form-select" name="{{$attribute->attr_title}}" id="attribute-{{$attribute->attr_id}}" aria-label="Default select example">
<option value="">Select {{$attribute->attr_title}}</option>
#foreach($attrValues as $attrValue)
#if ($attrValue->attr_id == $attribute->attr_id && strlen($attrValue->value) > 0 )
<option value="{{$attribute->attr_id}}-{{$attrValue->value_id}}" > {{$attrValue->value}}</option>
#endif
#endforeach
</select>
</div>
<div class="inputError"> #error("{$attribute->attr_title}") Error: {{ $message }} #enderror </div>
#endforeach
#endif
<div>
<button type="submit" class="btn btn-primary mt-3 px-4">Save</button>
</div>
</form>
CODE IN CONTROLLER IS :
$fields = $req->input();
$ValidationRules=[];
foreach($fields as $fieldName=>$fieldvalue){
if($fieldName == "assetTitle"){
$ValidationRules[$fieldName] = 'required|unique:assets,title';
}else{
$ValidationRules[$fieldName] = 'required';
}
}
$req->validate($ValidationRules);
I guess you have made some changes in resources/lang/en/validation.php file.
in this or any language you have set , there is a attribute named attributes
that you can change the the attribute name displaying in error message.
because the error message of asset field is ok I do not think it's a general error . check this file and attributes or messages key in it.
Don't know if you still need help but I just had the same issue and I think it's because you might have the input names with text uppercase, laravel automaticly adds a space for each uppercase character in the name attribute when showing the errors.
For example:
name="thisModel"
Will display as:
... this Model ...
If you have:
name="MODEL"
Will display as:
... M O D E L ...
Hope this helps someone in the future x)
Related
I have a form where a user can choose his/her civil status. And I have a separate table for the civil status that I queried and displayed the option through the controller into the blade file. The problem is, I cant display the selected value of the $user->civil_status in the blade file. Ill provide the code down below
Controller.php file
public function get_civil_status($id)
{
$statuses = CivilStatusModel::all();
$opt="<option>Select Civil Status</option>";
foreach($statuses as $status)
{
if($status->id > 0) {
if($id == $status->id){
$opt.="<option value={$status->id} selected>{$status->complete_name}</option>";
} else {
$opt.="<option value={$status->id}>{$status->complete_name}</option>";
}
}
}
return $opt;
}
public function dashboard($id){
$data = UserModel::where('seq_id','=',Session::get('loginId'))->first();
$data['optStatus']=$this->get_civil_status($id);
return view ("home.dashboard", $data);
}
Blade.php file
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="civilStatus" class="col-sm-3 text-right control-label col-form-label">Civil Status</label>
<div class="col-sm-9">
<select class="form-control" type="date" id='civilStatus' >
{{!! $optStatus !!}}
</select>
</div>
</div>
</div>
You might provide links or show the solution in the answer, anything that will help me improve will be appreciated
It looks like you're trying to access the variable $optStatus in your blade template. However, in your controller you only pass the variable $data which does contain the first variable. You can access the data by {{!! $data['optStatus'] !!}}
Also, as you asked about showing you refactoring in your comment, here's how to use blade's conditional and looping patterns:
Controller.php:
public function get_civil_status()
{
$statuses = CivilStatusModel::all();
return $statuses;
}
public function dashboard($id){
$data = UserModel::where('seq_id','=',Session::get('loginId'))->first();
$optStatus = $this->get_civil_status();
return view ("home.dashboard", ['optStatus'=>$optStatus,'id'=>$id]);
}
template.blade.php:
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="civilStatus" class="col-sm-3 text-right control-label col-form-label">Civil Status</label>
<div class="col-sm-9">
<select class="form-control" type="date" id='civilStatus' >
#foreach($optStatus as $status)
#if($status->id > 0)
#if($id == $status->id)
<option value={$status->id} selected>{$status->complete_name}</option>
#else
<option value={$status->id}>{$status->complete_name}</option>
#endif
#endif
#endforeach
</select>
</div>
</div>
</div>
I would further refactor it to say the selected user in one line rather than your conditional #if - #else - #endif
It would look something like this:
<option value={$status->id} #if($status->id == $id) selected #endif>{$status->complete_name}</option>
With the line above, you would be able to drop your most inner if else loop as the selected attribute is the only change in both elements.
Here's a reference to the blade templating library in laravel.
https://laravel.com/docs/9.x/blade
Lastly, as a hint to letting Laravel do the heavy lifting, check out Auth::user()
Rather than accessing your session and then querying a user, it should be done for you already in most cases unless you're using a very barebones instance of Laravel
I am a beginner in Laravel. I want to implement a feature that:
I want to use Laravel 8 and PHP:
Select a part of the data in a table (via a select)
how to get the id selected in the select :
-> get the identifier selected in the option tag in order to use it in an sql query that combines selection and insertion
Copy the data and insert it in another table (via an add button)
how to recover the id present in the url of the page
Display the data inserted in a table
no problem
<select name="id_segment" class="form-control">
<?php
$req1 = DB::select("SELECT id_segment, nom_segment FROM `segements` ");
foreach ($req1 as $re1 => $r1) {
?>
<option name="id_segment" value="{{ $r1->id_segment }}"> {{ $r1->id_segment }}
{{ $r1->nom_segment }}</option>
<?php
} ?>
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary" id="AjoutSegment">Ajouter</button>
<a class="btn btn-primary" href="{{ route('groupecampagnes.index') }}"> Back</a>
</div>
I have already tried with $_POST and $_GET while making a var_dump, but I have seen that some people say that it does not work, me it gave me the display of an error with the id that I seek to recover precisely, whereas it should just display it to me on the page to see if I recover it well and truly. The var_dump is not present in the code because I removed it in the meantime. After I tried various solutions found on the net, which have me display as error for some of them that I had to do with a std class object.
Assuming your code is in a file called page and stored in the views directory (resources/views/page.blade.php), you could go to your controller and pass the needed data to your view like this:
$segments = DB::select("SELECT id_segment, nom_segment FROM `segements` ")->get();
return view('page', compact('segments'))
Then you can use it in your view:
<select name="id_segment" class="form-control">
#foreach ($segments as $r1)
<option name="id_segment" value="{{ $r1->id_segment }}"> {{ $r1->id_segment }} {{ $r1->nom_segment }}</option>
#endforeach
</select>
I have a dropdown and text input in a form. Form creates a course and I want to select classroom for course from dropdown and write its capacity to text input. But a course may have mutiple classrooms. How can I keep these classrooms and their capacity and show them in a table under the form?Like this:
Here's my code that keeps only one classroom and capacity
<div class="sm:col-start-1 sm:col-end-3 col-span-3 ">
<x-select x-on:change="isShowing = $event.target.value" name="classroom_id" label="{!! __('Classroom') !!}" wire:model="classroom_id"
id="classroom_id"
:options="$this->classrooms"/>
<x-jet-input-error for="classroom_id" class="mt-2" />
</div>
<div class="col-span-2 sm:col-span-1 " x-show="isShowing">
<label class="tf-form-label" for="capacity">
{{ __('Capacity') }}
</label>
<input wire:model.debounce.250ms="capacity" type="text" name="capacity" id="capacity" class="tf-input" />
<x-jet-input-error for="capacity" class="mt-2" />
</div>
$this->form->save();// firstly course saved
$classroom = new Classroom();
$classroom->course_id = $this->form->id;
$classroom->classroom_id = $this->classroom_id;
$classroom->capacity = $this->capacity;
$classroom->save();
Add the following codes in your component.
Component
public $classroom_id, $capacity;
$course = Course::create($validatedCourseData); // firstly course saved
// $this->classroom_id is array, because we set "multiple" in blade file
$course->classrooms()->attach($this->classroom_id);
Blade
Please add multiple in in your select box code.
<div class="sm:col-start-1 sm:col-end-3 col-span-3 ">
<x-select x-on:change="isShowing = $event.target.value" name="classroom_id" label="{!! __('Classroom') !!}" wire:model="classroom_id"
id="classroom_id"
:options="$this->classrooms" multiple/>
<x-jet-input-error for="classroom_id" class="mt-2" />
</div>
<div class="col-span-2 sm:col-span-1 " x-show="isShowing">
<label class="tf-form-label" for="capacity">
{{ __('Capacity') }}
</label>
<input wire:model.debounce.250ms="capacity" type="text" name="capacity" id="capacity" class="tf-input" />
<x-jet-input-error for="capacity" class="mt-2" />
</div>
good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
I am doing a form where the user can update his information. The form shows several inputs and the info retrieved from the database is displayed inside them.
I have noticed that, when the info is displayed, one extra space is added. For example, if i retrieve a date '1965-08-29', then in the form i notice that an extra space is added at the end: '1965-08-29 '.
This is happening in all inputs causing validation fails.
Here is a sample code about how i retrieve the data inside the controller:
$id_user=Auth::user()->id;
$usuario=User::find($id_user);
if(isset($usuario->nombre_pila)){$nombrepila=$usuario->nombre_pila;}else{$nombrepila='';}
if(isset($usuario->ap_paterno)){$ap_paterno=$usuario->ap_paterno;}else{$ap_paterno='';}
if(isset($usuario->ap_materno)){$ap_materno=$usuario->ap_materno;}else{$ap_materno='';}
Here is how i send these data to the view:
return View::make('profile.edit',array('id_user'=>$id_user, 'nombrepila'=>$nombrepila, 'ap_paterno'=>$ap_paterno,'ap_materno'=>$ap_materno));
Here are some examples of the inputs in the view:
<div class="form-group #if ($errors->has('nombre_pila')) has-error #endif"><!--Nombre de pila-->
<label for="nombre_pila" class="col-sm-2 control-label">Nombre(s) de pila:</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="nombre_pila" name="nombre_pila" maxlength="45" value="#if(isset($nombrepila)){{$nombrepila}} #endif">
</div>
#if($errors->has('nombre_pila'))
{{$errors->first('nombre_pila')}}
#endif
</div><!-- ----------fin nombre de pila ------------ -->
<div class="form-group #if ($errors->has('ap_paterno')) has-error #endif"><!--apellido paterno-->
<label for="ap_paterno" class="col-sm-2 control-label">Apellido paterno:</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="ap_paterno" name="ap_paterno" maxlength="45" value="#if(isset($ap_paterno)){{$ap_paterno}} #endif">
</div>
#if($errors->has('ap_paterno'))
{{$errors->first('ap_paterno')}}
#endif
</div><!-- ----------fin de apellido paterno ------------ -->
I am using bootstrap 3 forms (i don't know whether this has to do with the problem or not)
It could be that i should use something like the rtrim() function. But if someone out there could explain me why this is happening or what i am missing to do, i'll appreciate it.
You have a space before your #endifs. To fix that either do
value="#if(isset($ap_paterno)){{$ap_paterno}}#endif"
or (a bit nicer in my opinion)
value="{{ (isset($ap_paterno) ? $ap_paterno : '') }}"