I have 3 form, the first is the form students with 2 fields (name, firstname)
Then, we have the form payments with 3 fields (date_encoding, price, fk_student)
And finally, the last form trainings with 3 fields (date_sitting, fk_student, fk_payment).
My problem is the form trainings, I can create a new record without the payment of a student.
Is it possible to block a record with an error message in the training form?
Here is an idea of my code for now.
public function store(Request $request)
{
$request->validate([
'date_sitting' => 'required|date',
'fk_student' => 'required',
'fk_payment' => 'required'
]);
$exists = Training::where('date_sitting', $request->get('date_sitting'))->where('fk_student', $request->get('fk_student'))->where('fk_payment', $request->get('fk_payment'))->count();
if (!$exists){
Training::create($request->all());
return redirect()->route('trainings.index')
->with('success', 'new data created successfully');
}
else{
return redirect()->route('trainings.index')
->with('error', 'duplicate');
}
}
Sure - just add an if-check inside the creation block. If the user doesn't have a payment, don't create and return an error message. You can do this by redirect like you have it, or you can even have a separate check via AJAX to just see if there is a payment, similar to the if-check I add below on $payment.
However, to keep it simple & continue as you have it, something like this:
if (!$exists){
// Is there a payment for the student trying to create a training?
$payment = Payment::where('fk_student', $request->get('fk_student'))->first()
// You may wish to add some kind of date check to see if they paid for a specific training
if(!isset($payment)){ // No payment = block creation and return error msg.
return redirect()->route('trainings.index')
->with('error', 'No Payment, no training for you!');
}
else{
Training::create($request->all());
return redirect()->route('trainings.index')
->with('success', 'new data created successfully');
}
}
Related
I am sending a update request like:
Route::put('user/{user}/edit-user-education', 'UpdateUserEducationController#editUserEducation');
My controller is :
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
}
Now how I can validate the request user_id with the user_id already in inserted in DB ? I want to ensure that the only user can update the record who created that one.
How to do so ? Thanks in advance
Check out the docs on validation here:
https://laravel.com/docs/8.x/validation
Specifically, I think you want the exists rule:
https://laravel.com/docs/8.x/validation#rule-exists
The quick and dirty way is to add your validation in the controller but there are some better methods as explained in the docs. I usually opt for Form Requests, which it looks like you've already done as your request is an instance of EditUserEducationRequest.
In the controller you can add:
$validated = $EditUserEducationRequest->validate([
'user_id' => 'required|exists:users',
]);
I assume your user table is called users.
You could alternatively state the exists validation rule for user_id in the rules array of your Form Request as per the docs.
EDIT:
I actually missed a requirement in your original post that is that the user sending the request must be the same user as the one being updated.
That can be handled in the the authorize method of your form request with something like:
public function authorize()
{
return $this->user()->id == $this->user_id;
}
Simply make a check that current user is the same user who is trying to update record.
class UpdateUserEducationController extends Controller
{
public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
{
if($user->id==Auth::user()->id){
$education->school = $request->school;
$education->degree = $request->degree;
$education->user_id = $user->id; // here to validate
$education->save();
return response()->json([
'message' => 'Education Updated'
]);
}
else{
return response()->json([
'error' => 'Invalid User'
]);
}
}
}
I am new in laravel, I trying to make custom validation from two tables,
i have table users (contain id,email, password,job_type) and
another table name employee with fields user_id,admin_type_id,
my problem is when I trying to check data with login user and confirm he is an employee with job_tybe =1 in table Employee and conform is type is admin by admin_type_id =1 when I make var_dump($admin) i get output is null
I found my problem is password registers in database not password that send from a form
how can I make password is I dental to make login
condition of login is job_tybe =1+ admin_type_id =1
this is my code:-
public function authenticate(Request $request)
{
$credentials = array(
'email' => $request->get('email'),
'password' => $request->get('password'),
);
//check user is employee
$admin=User::where(['email' => $credentials['email'],'password' =>Hash::make($credentials['password']) ,'deleted'=>1,'status'=>1,'job_type'=>1])->first();
//get admin type
$adminType=Employee::where(['id_user' => $admin->id, 'admin_type_id'=>1,'deleted'=>1,'status'=>1])->first();;
if($adminType !=null)
{
if (Auth::attempt($credentials)) {
return redirect()->route('brand.create');
exit();
}
return redirect()->back()->with("messageError","Invalid Email Or Password");
}
To make password use "bcrypt('password')" method.
In my administrator panel, I have 2 Roles, admin and former:
For now, I have 3 users:
the first role is admin, the pseudo is admin and email address is admin#gmail.com
the second role is former, it has like pseudo Remace and email address is test#gmail.com
the third user is always a former, it has like pseudo Gofette and email address is ledeluge1990#gmail.com
For information, the administrator is the only one to create records.
Here, I have 2 recordings: (It's the informations of the formers)
Now, my goal is that each former has access to his informations.
So, the first former is Remace with email adresse test#gmail.com.
I log in with email adresse of Remace ( test#gmail.com )
I see this :
In fact, I retrieve the informations of Gofette and not those of Remace, why ???
Now, I want to connect with the user Gofette with email adresse ledeluge1990#gmail.com...
I see nothing ???
I think my problem is in my function index() ????
public function index()
{
if($has_role = auth()->user()->hasRole('admin')){
$garages = Garage::oldest()->paginate(5);
return view('admin.garages.index', compact('garages'));
} else{
$garages = Garage::where('id', Auth::user()->id)->paginate(5);
return view('admin.garages.index', compact('garages'));
}
}
public function create()
{
$localites = Localite::all();
return view('admin.garages.create', compact('localites', 'garages'));
}
public function store(Request $request)
{
$request->validate([
'nom' => 'required|string|max:25|min:3|alpha',
'adresse' => 'required|string|max:50|min:12',
'fk_localite' => 'required',
'telephone' => 'required|string|min:8|max:11',
'email' => 'required|email|max:25|min:10'
]);
$exists = Garage::where('nom', $request->get('nom'))->where('adresse', $request->get('adresse'))->where('fk_localite', $request->get('fk_localite'))->where('telephone', $request->get('telephone'))->where('email', $request->get('email'))->count();
if (!$exists){
Garage::create($request->all());
return redirect()->route('garages.index')
->with('success', 'Un nouvel enregistrement a été effectué');
}
else{
return redirect()->route('garages.index')
->with('error', 'Doublon, cet enregistrement existe déjà! ');
}
}
Thanks a lot for your help.
As stated by the comment above your $garages = Garage::where('id', Auth::user()->id)->paginate(5);. It's searching for Garage records with an id matching the user's id.
To solve this problem, you can :
Change the query to : $garages = Garage::where('email', Auth::user()->email)->paginate(5);
Or create another user_id field in garages table to assign each of the former to their garages.
Hello stackoverflow geeks, I'm in my final stages of the laravel learning curve all thanks to you guys.
However, i need to generate a warning message like "You cannot delete a role assigned to a user" every time a user tries to delete a role assigned to a user.
instead it loads a page with an sql error. how to i do it?
And how do i avoid a password that has been already been stored from being hashed again. eg:- $2y$10$p8JwI5P4yE2UFo2.vHP99.0dP2jU7ll/9w73IzUa9/yegKOSTHJWq is always hashed every time i edit a user's information.
Thanks you all who've made learning laravel easy for me by answering in time
code
public function destroy(Request $request,$id)
{
// delete
// $role = Role::find($id);
//$role->delete();
$role = Role::find ($id);
if ($role->users() !=null) {
return redirect()->back()->withInput(['warning' => 'Not allowed']);
}
$role->delete();
// redirect
Session::flash('message', 'Record successfully deleted!');
Session::flash('alert-type', 'success');
return Redirect::to('role');
}
This highly depends on how you want to handle the errors. You can either catch the sql exception and display your custom error OR what is probably better for you is to handle the incoming request, validate it and return an error if validation fails.
Here are the validation docs : https://laravel.com/docs/5.3/validation
You have multiple options on how to validate a request. Simple example to validate a title is unique in the table posts and is maximum 255 chars long:
$this->validate($request, [
'title' => 'required|unique:posts|max:255'
]);
If you cannot find a rule that is helping you simply define your own validation rule https://laravel.com/docs/5.3/validation#custom-validation-rules
Ofcourse you can also do the validation manually. In your request or in your controller (depends on your setup) just check for it
// assuming you want to delete an entry
public function delete(Request $request, $id)
{
$role = App\Role::findOrFail($id);
if ($role->users() != null) {
return redirect()->back()->withInput(['message' => 'Not allowed']);
// now you can output $message
}
$role->delete();
return ...
}
I'm creating a registration form using codeigniter. I understand that there is a validation for each field in CI but what I want to do is to validate a multiple field exist.
SELECT emp_id FROM emp_record WHERE firstname = 'firstname' AND lastname = 'firstname' AND birthdate = 'firstname'
If the query above find a match I want to alert on my view page that the record already exist.
Please help.
Appreciate it. Thanks.
Declare a custom callback function
function _check_firstname()
{
$firstname = $this->security->xss_clean($this->input->post('firstname'));
$array = array('firstname' => $firstname, 'birthdate' => $firstname);
$result = $this->db->select('emp_id')->from('emp_record')->where($array)->get();
if($result->num_rows())
{
$this->form_validation->set_message('_check_firstname', 'Record already exists');
return false;
}else
{
return true;
}
}
Set rules including (callback__check_firstname)
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|callback__check_firstname');
Now, when you'll check validation like
if ($this->form_validation->run()){
// passes
}
else{
// not passes, so show the view again
}
In the view, if you have something like this
<?php echo form_error('firstname') ?>
This will show the error message set in the custom callback function.
You could use num_rows() to do such things.
By using active record you can achieve this by doing the following
$qry = $this->db->select('emp_id')->from('emp_record')
->where('firstname', $firstname)
->where('lastname', $lastname)
->where('birthdate', $birthdate)
->get();
if ($qry->num_rows() > 0)
return TRUE;
else
return FALSE;
This will return TRUE if it finds at least one row in your database or FALSE if it finds nothing.
some people can/may have the same firstname,lastname and birthdate
But still if you want to have it that way you could create a callback validation
here is a snippet.
public function checkinput()
{
// you may want to sanitize the input
$data['fname'] = $this->input->post('fname');
$data['lname'] = $this->input->post('fname');
$data['mname'] = $this->input->post('fname');
//your model for checking data must return TRUE or FALSE
if($this->model->method_for_checking($data))
{
this->form_validation->set_message('checkinput', 'Duplicate data exists.');
return TRUE;
}else{
return FALSE;
}
}
Now you can use it on your validation rules i.e
$this->form_validation('fname','fname',callback_checkinput);
Other options are
Extend a form validation and create a validation rule there as not
to clutter the controller
Or ,After Submitting the form before inserting the data, you can check whether it is a duplicate and do the logical things their.