Route [staff] not defined while it is in laravel? - 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

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']);

Call to a member function getClientOriginalExtension() on null in laravel?

When I'm submitting the image, it shows the following error:
Call to a member function getClientOriginalExtension() on null
I do not know, where the mistake is.
This is my controller named ProductController:
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'brand' => 'required',
'detail' => 'required',
'size' => 'required',
'type' => 'required',
'price' => 'required',
'image' => 'required',
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'image' => $new_name,
'name' => $request->input('name'),
'size' => $request->input('size'),
'type' => $request->input('type'),
'price' => $request->input('price'),
'detail' => $request->input('detail'),
'brand' => $request->input('brand'),
);
Product::create($form_data);
return redirect()->route('product.index')->withSuccess('Done');
}
The error occours on this line: $new_name = rand().'.'.$image->getClientOriginalExtension();
This is my form from where I am submitting the image:
<form id="myForm" method="post" action="{{ route('product.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="brand" required="">
<label>Brand</label>
#error('brand')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="price" required="">
<label>Price</label>
#error('price')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box" style=" border-bottom: 1px solid white">
<span style="font-weight: bold; color: white; font-size: 16px; margin-bottom: 30px ">Size</span>
<select name="size" id="size" style="width: 40px; font-size: 16px; margin-bottom: 20px ">
<option value="50 ML">50 ML</option>
<option value="100 ML">100 ML</option>
<option value="200 ML">200 ML</option>
<option value="500 ML">500 ML</option>
<option value="1 L">1 L</option>
<option value="4 L">4 L</option>
<option value="10 L">10 L</option>
<option value="20 L">20 L</option>
</select>
#error('size')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="type" required="">
<label>Type</label>
#error('type')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
<input type="text" name="detail" required="">
<label>Detail</label>
#error('detail')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="user-box">
Image<input type="file" name="image" required="">
<label>Image</label>
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button class="a" id="a" value="submit" name="submit">Submit</button>
</form>
your server is not receiving the file that you are uploading,
Try adding the enctype='multipart/form-data' to the form in blade file.
<form id="myForm" method="post" action="{{ route('product.store') }}" enctype='multipart/form-data'>
Add attribute enctype="multipart/form-data" to your form tag like below:
<form id="myForm" method="post" action="{{ route('product.store') }}" enctype="multipart/form-data">

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.

Why is my errormessage not showing in 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

How to change password?

I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}

Resources