Why is my errormessage not showing in Laravel - laravel

I have a select input on my form and when the user does not select a value I want to show an error. For some reason the error is not showing, although almost the same code does on another form.
The code that is working:
<div class="form-group row">
<label class="md-col-4 col-form-label text-md-right" for="slesson-date">Datum</label>
<div class="col-md-6">
<input id="slesson-date" class="form-control #error('date') is-invalid #enderror" type="date" name="date" required value="{{old('date', date('Y-m-d'))}}">
#error('date')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
The code that is not working:
<div>
<select name="code" class="selectpicker form-control" data-live-search="true" data-live-search-normalize="true" data-style="btn-secondary" title="Zoek een leerling">
#foreach($students as $student)
<option value={{$student->code}}>{{$student->name}}</option>
#endforeach
</select>
#error('code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
Both input fields are validated using formrequests.
When I show all the errors on the end of the view the error is show so it is available, just not recognized by the #error('code') for some reason.
Edit:
I added the controllercode as per request.
public function sLessonsStudent(ValidateSLessonStudent $request)
{
$validated = $request->validated();
$code = $validated['code'];
$sLessons= SLesson::whereHas('studentProperty',function($query) use ($code){
$query->where('user_code',$code);
})->select('date','hour','classroom_number')->oldest('date')->orderBy('hour')->get();
$user = User::where('code',$code)->first();
$sLessonsJson = $sLessons->toJson();
return view('sAdmin.sLessonsStudent',compact('sLessonsJson','user'));
}
And the formrequest validating the request:
class ValidateSLessonStudent extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'code'=>['required']
];
}
/**
* {#inheritDoc}
* #see \Illuminate\Foundation\Http\FormRequest::messages()
*/
public function messages()
{
return [
'code.required'=>'Er moet een leerling gekozen worden!'
];
}
}
Update 2:
The error is in the ErrorBag
ViewErrorBag {#438
#bags: array:1 [
"default" => MessageBag {#439
#messages: array:1 [
"code" => array:1 [
0 => "Er moet een leerling gekozen worden!"
]
]
#format: ":message"
}
]
}

After a long time of trial and error I found the problem.
The class "invalid-feedback" in the following code
#error('code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
needs to preceded with a form control with form-control #error('code') is-invalid #enderror". This is true for the working code where the input has the required classes, but not for the second code where the select has only the class form-control and not the addition #error directive.

The problem can be solved by adding "d-block" to the class:
#error('code')
<span class="invalid-feedback d-block" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror

Related

The relationship between users and courses and categories

I want to be able to see, for example, only a certain group that is in that category among the courses that I offer on the site.
Anyone can not see the course of another group
In this way, when registering, users choose the category they are in and see the information about their group in their profile.
Should I use polymorphic?
User table
Course table
Classification table
And another table called categorizable which is polymorphic how many to how many?
please guide me
database
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->integer('parent')->default(0);
$table->foreignId('category_id')->nullable()->constrained('categories')->onDelete('cascade');
$table->timestamps();
});
Schema::create('categorizables' , function(Blueprint $table) {
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('categorizable_id');
$table->string('categorizable_type');
});
model category
public function courses()
{
return $this->morphedByMany(Course::class , 'categorizable');
}
public function users()
{
return $this->morphedByMany(User::class , 'categorizable');
}
model user and course
public function categories()
{
return $this->morphToMany(Category::class, 'categorizable');
}
form blade
<form class="g-3" method="POST" action="{{ route('register') }}">
#csrf
<div class="col-8 m-auto">
<input type="text" required class="form-control #error('name') is-invalid #enderror" id="name" name="name">
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<input type="text" required class="form-control #error('national_code') is-invalid #enderror" id="national_code" name="national_code">
#error('national_code')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<select id="inputState" class="form-select" name="category_id">
<option selected class="d-none">select category</option>
#foreach(\App\Models\Category::all() as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="col-8 m-auto">
<input type="password" required class="form-control #error('password') is-invalid #enderror" id="password" name="password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-8 m-auto">
<input type="password" required class="form-control #error('password_confirmation') is-invalid #enderror" id="password_confirmation" name="password_confirmation">
#error('password_confirmation')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit">register</button>
</form>
controller
$data = $request->validate([
'name' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'national_code' => ['required' , New Nationalcode],
// 'g-recaptcha-response' =>['required' , New Recaptcha],
'category_id' => 'required',
]);
// $user = User::create($data);
$user = User::create([
'name' => $data['name'],
'password' => Hash::make($data['password']),
'national_code' => $data['national_code'],
// 'category_id' => $data['category_id'],
]);
$user->categories()->sync($data['category_id']);

Route [staff] not defined while it is in laravel?

Route [staff] not defined.
This is my web.php (route).
Route::get('/staff', function () {
return view('staff');
});
Route::resource('/staff', StaffController::class);
This is my controller. The index, create page is in same page.
public function index()
{
$staffs = Staff::all();
return view('staff', compact('staffs'));
}
public function create()
{
return view('staff');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'gender' => 'required',
'salary' => 'required',
]);
$staff = new Staff();
$staff->name = $request->name;
$staff->gender = $request->gender;
$staff->salary = $request->salary;
$staff->save();
return redirect()->route('staff')->withSuccess('Done');
}
And this is my staff.blade.php where after click on submit error occuring (route not defined).
<form id="myForm" method="post" action="{{ route('staff.store') }}">
#csrf
<div class="user-box">
<input type="text" name="name" required="">
<label>Name</label>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="gender" required="">
<label>Gender</label>
#error('gender')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="salary" required="">
<label>Salary</label>
#error('salary')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button class="a" id="a" value="submit" name="submit">Submit</button>
</form>
There are no any name route called staff, it would be staff.index :
return redirect()->route('staff.index')->withSuccess('Done');
See Resource Route Name
1st remove your get route all is covered by resource
Route::resource('/staff', StaffController::class);
this code generate route names like
Route Name
staff.index
staff.create
staff.store
staff.show
staff.edit
staff.update
staff.destroy
so in your code you need to do this
return redirect()->route('staff.index')->withSuccess('Done');
ref link https://laravel.com/docs/8.x/controllers#actions-handled-by-resource-controller

laravel create eloquent on mass assignment $request->all() a single field is always null

i have used create eloquent and i used massassignment($request->all()) for saving data but only "feede_quantity" column is always null. I have print the request->all() and its showing all the form data including "feeder_quntity" but while creating its value is null. i have given my model,controller and blade code and also added the database image. Please tell me what is wrong here. Thank you
**My Model**
protected $table = 'ebay_accounts';
protected $fillable = ['id','developer_id','feeder_quantity','account_name',
'authorization_token','access_token','refresh_token','session_id','expiry_date'];
protected $dates = ['deleted_at','created_at','updated_at'];
**My controller**
public function storeAuthorization(Request $request){
$result = EbayAccount::create(['developer_id' => $request->developer_id,'feeder_quantity' => 5]);
$account_site = EbayAccount::find($result->id);
$account_site->sites()->attach($request->site_id);
return redirect('ebay-account-list')->with('success','account created successfully');
}
**myblade file**
<div class="form-group row">
<div class="col-md-1"></div>
<label for="feeder_quantity" class="col-md-3 col-form-label ml-sm-25 mr-sm-25 ml-xs-25 mr-xs-25 required">Feeder Quantity</label>
<div class="col-md-7 ml-sm-25 mr-sm-25 ml-xs-25 mr-xs-25">
<input id="feeder_quantity" type="number" class="form-control #error('feeder_quantity') is-invalid #enderror" name="feeder_quantity" value="" maxlength="80" onkeyup="Count();" required autocomplete="name" autofocus>
<span id="display" class="float-right"></span>
#error('feeder_quantity')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-1"></div>
</div>
**database table value is always empty for feeder_quantity**

Reset password manually via answering the security questions without sending email - Laravel/auth

I am currently developing a simple Bookstore application with a few numbers of users on which sending emails are not needed because it will be implemented in local system so is there any way to customize laravel-auth for password reset function by adding a few security questions fields where user can reset his/her password without sending reset links via email.
Any kind of help will be highly appreciated.
here I tried the below code but id did not work
Code in web.php
Route::post('/main/checklogin', 'UserController#chekQuestions');
Code in userContoller
public function chekQuestions(Request $request)
{
$request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::first();
if($user->email == $request->email && $user->answerQuestionOne == $request->answerQuestionOne && $user->answerQuestionTwo == $request->answerQuestionTwo )
{
// $userEmail = DB::table( 'password_resets' )->where( 'token', $user->token );
// return view('auth.password.reset',compact($userEmail));
return view('auth.password.reset');
}
return response()->json( [
'error' => true,
'message' => 'We cannot find a user with that Email Address'
], 404 );
}
Code in reset password.blade
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="POST" action="{{ url('/main/checklogin') }}" >
#csrf
<h3>د پټ نو بیا راګرځولو لپاره لاندی امنتی پوښتنو ته ځواب ورکړی </h3>
<div class="form-group has-feedback">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="form-control-feedback">
<i class="fa fa-envelope-o text-muted"></i>
</div>
</div>
<div>
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div>
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit" class="btn btn-default btn-block">خوندی کړی </button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">
تاسو دمخه غړی یاست ننوتل
</p>
<div class="clearfix"></div>
<br />
</form>
</section>
</div>
You don't need Laravel implementation for this. Just Find a user with the given email and check the answers. After that update the user record with the new password.
In order to fetch user you should do this:
$data = $request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::where(['email' => $data['email'])->first();
After this just check the answers.
You also need to take the new password from user.

Laravel: $errors->first() doesn't show error. How to make it work?

I want to show validation errors below each form element. I used {{ $errors->first('control1') }} but, it does not show the validation errors.
No clue about how to get around with this.
Below is my view code snippet.
<div class="form-group row">
<label for="control1" class="col-md-4 col-form-label text-md-left">{{ __('Number of control1') }}</label>
<input type="number" class="form-control col-md-8" id="control1" name="control1" value="{{ old('control1', 2) }}" required minvalue="1" />
#if ($errors->has('control1'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('control1') }}</strong>
</span>
#endif
</div>
in controller action, thebelow validation is written.
$this->validate($request, [
'control1' => 'required|min:1',
]);
You are validating a field named sprints. So change your validator array to match that, from this:
$this->validate($request, [
'sprints' => 'required|min:1',
]);
to this:
$this->validate($request, [
'control1' => 'required|min:1',
]);
And depending on your laravel version you can even simplify it like this:
$request->validate([
'control1' => 'required|min:1',
]);
Then in your view write this:
#error('control1')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror

Resources