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.
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.
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');
}
}
I am doing a peer marking system which requires a function that lecturer adds id list and when students enroll in a course, he enters his id needed to match the id on lecturer id list.
Controller
public function store(Request $request)
{
$this->validate($request, [
'course_code' => 'required',
'studentid' => 'required'
]);
$enrollment = new Enrollment;
$enrollment->user_id = auth()->user()->id;
$enrollment->course_id = $request->course;
$enrollment->user_StudentID = $request->studentid;
$input_course_id = $request->input('course_code');
$input_studentid = $request->input('studentid');
$course = Course::find($enrollment->course_id);
$course_identifiers = $course->identifiers;
// Need all the data in the database course table for comparison
//$course represents the contents of the course table in all databases, then you need to loop first, then judge
//$course stands for list $signleCourse for each piece of data
foreach ($course_identifiers as $course_identifier) {
// if ($course_identifier->studentid == $input_studentid )
if ($input_studentid == $course_identifier->studentid) {
if ($request->course == $input_course_id) {
//if true,save and redirect
$enrollment->save();
return redirect('/enrollment')->with('success', 'Course Enrolled');
} else {
return redirect('/enrollment')->with('error', 'Please Enter Correct Confirmation Code');
//If false do nothing
}
} else {
return redirect('/enrollment')->with('error', 'Please Enter Correct Student ID');
//If false do nothing
}
}
}
It can only match the first value, but other values I enter cannot be recognized.
Turn off your redirects. It's really hard to understand the context of that code but it looks like if it fails to match it redirects so doesn't go through the second and subsequent values of $course_identifiers.
I am having an error... I don't know how to fix this...
I am doing something that will set page privileges to admin employee and other roles.
But suddenly I doesn't get the value of my variable role.
public function login(Request $req)
{
$username=$req->input('email');
$password=$req->input('password');
$breadcrumb = 'Dashboard';
$pageTitle = 'CollabUX | Dashboard';
$prepath ='../';
$currentURL = Req::url();
$user = DB::table('add_users')->where(['username'=>$username,'password'=>$password])->get();
if(count($user)>0){
session(['isloggedin' => 'true']);
session(['roles' => $user->role]);
return View::make('dashboard')->with(
array('breadcrumb' => $breadcrumb,'pageTitle' => $pageTitle,'currentURL' => $currentURL,'prepath' => $prepath));
}
else{
//redirect page
$data = array(
'error' => 1,
'remarks' => 'Invalid Username/Password. Please try again.'
);
return View::make('login')->with('data', $data);
}
}
Well, there are two solutions.
You can define a user in code as admin
or you can create a separate table
userroles (id, title)
then you have to check with your requirements.
if only one user can have only role
then add userrole_id in users table and update accordingly.
if one user can have multiple roles
then create a separate table
users_to_userroles (id, user_id, userrole_id)
and it will be a pivot table.