I am going to insert and update values using my addpermission function in my Controller
public function addPermission(Request $request, $id, $permission = null)
{
$this->validate($request, [
'status' => 'required'
]);
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($permission,['id'])->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
My routes
Route::post('projects/{project_id}/permission', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);
Data insert works properly, but update doesn't work.
When I click button to update it is inserts as new record to the database.
My table name is permission and have the following columns
id (autoincrement)
status
project_id
collaborator_id
What do I need to change to make the updating work?
I see an error in this line, this should return the permission object not the id of permission.
$permission = Permission::findOrFail($permission,['id'])->id;
Change to,
$permission = Permission::findOrFail($permission['id']);
You should write this. Hopefully This will solve your problem
public function addPermission(Request $request, $id, $permission)
{
$this->validate($request, [
'status' => 'required'
]);
$per = Permission::where('id', $permission)->first();
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($per)->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
I think you may need to put an optional route parameter in for permission id.
Route::post('projects/{project_id}/permission/{permission_id?}', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);
Related
I have a Laravel 8 project. I want to change magic auth error message. And I did updated my code like this.
'This code has already been used' I replaced this message with this in the context of the code 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.'
OLD AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'This code has already been used.']);
}
return redirect()->route('login');
}
NEW AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.']);
}
return redirect()->route('login');
}
But when I try now, I see that the message has not changed. How can I fix this?
Please follow below steps:
If you haven't done it yet, delete or rename the old AuthController class, use only new one, with new message.
Make sure routes going to the methods in the new controller
Run composer dump-autoload.
If the problem still persist I'd check whether some kind of cache mechanism is enabled in php, like opcache.
I'm currently working on a project that has an accounts management section where the system admin creates the user accounts.
The [Users] table has a column named "Organization_name", which is the user's represented organization. After submitting the form, "Organization_name" will then be also added to the [Organization] table, under the [name] field. The two tables are related by the "user_id" column (taken from the "id" column of the [Users]).
I managed to create a working code to add a [Users] account that also adds the organization_name to the [Organization] table, although now I'm wondering how can I make a function that will also edit the rows in the [Organization] table whenever I edit the fields in [User].
(ex. I changed the "organization_name" field in [Users] with id=1 from "Organization A" to "Organization B," the "name" field in [Organization] with user_id=1 should also change from "Organization A" to "Organization B" too).
NOTE: "role_id" determines what kind of account permissions a user account will have, it doesn't affect the question but I'll leave it in the code snippet below just in case.
I'll attach the codes that I used below:
UserController.php
private static function createUser(Request $request)
{
$user = new User();
$user->email = $request->get('email');
$user->organization_name = $request->get('organization_name');
$user->password = Hash::make($request->get('password'));
$user->role_id = $request->get('role_id');
return $user;
}
private static function createSubUser(Request $request, $user_id)
{
$role_id = $request->get('role_id');
if($role_id == 1)
{
$sub_user = new Organization();
$sub_user->user_id = $user_id;
$sub_user->name = $request->get('organization_name');
}
elseif($role_id == 2)
{
$sub_user = new Staff();
$sub_user->user_id = $user_id;
}
elseif($role_id == 3)
{
$sub_user = new Administrator();
$sub_user->user_id = $user_id;
}
return $sub_user;
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string|email|max:255|unique:users',
'organization_name' => 'required|string|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = static::createUser($request);
$user->save();
$sub_user = static::createSubUser($request, $user->id);
$sub_user->save();
}
public function updateUserInfo(Request $request)
{
$user = User::find($request->id);
if($user->email == $request->email){
$check_email = false;
}
else{
$check_user = User::where('email', $request->email)->first();
if (!empty($check_user)) {
$check_email = true;
}
else {
$check_email = false;
}
}
if($check_email === true)
{
return response()->json([
'success' => false,
'error' => "User with the registered email of {$request->input('email')} already exists",
]);
}
else
{
$user = User::where('id', $request->id)->update([
'email' => $request->input('email'),
'organization_name' => $request->input('organization_name'),
'role_id' => $request->input('role_id')
]);
return response()->json([
'success' => true,
'user' => $user
]);
}
}
Thank you!
Why you need to add user_id on organization??
An organzation should have many students or users.No need to store organization_name on users table just save the id of organization.When you need to update organization name just update it on organization table.Because you don't need to change in user table you just save here id. Feel free to comment if you have any confussion.
If you set relation ships between the User.php return $this->belongsTo('App\User'); and Profile.php return $this->hasOne('App\Profile', 'user_id', 'id'); how can u get a corresponding user to the profile when you only get the Profile variables. public function update(Request $request, Profile $profile)
i was thinking of something like this User::where(user->id==$profile->id); but its not working how would can you do it?
mine hole function:
if(\Auth::check()) {
if(\Auth::user()->type == 'admin'){
$validated = $request->validate([
'username' => 'required',
'email' => 'required|email',
'firstname' => 'required',
'lastname' => 'required',
'age' => 'required|numeric|max:150',
'birthdate' => 'required|numeric',
'bio' => 'required|min:30',
'select_file' => 'image|mimes:jpg,png,gif,jpeg|max:2048'
]);
$image = $request->file('select_file');
$new_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$profile->username = $validated['username'];
$profile->email = $validated['email'];
$profile->firstname = $validated['firstname'];
$profile->lastname = $validated['lastname'];
$profile->age = $validated['age'];
$profile->birthdate = $validated['birthdate'];
$profile->bio = $validated['bio'];
$profile->image_path = $new_name;
$profile->update();
$user = User::where(user->id==$profile->id);
$user->name = $validated['username'];
$user->email = $validated['email'];
$user->update();
return redirect()
->route('admin')
->with('succes', 'Profile updated succesfully');
} else {
return redirect()
->route('admin')
->with('fail', 'Profile is unable to be update successfully');
}
} else {
return redirect()
->route('login')
->with('fail', 'Profile is unable to be update successfully
because ur not an Admin');
}
Your where is not formatted properly. You need to pass in 2 (or 3) parameters, where the first is the column, and the second is the value you're checking for. If using 3 parameters, the second would be the operator (= or !=). Don't forget first() (for one record) or get() (for a collection of records), so that the query actually runs. Otherwise, it will just be the QueryBuilder object.
User::where('id', $profile->user_id)->first();
or
User::where('id','=', $profile->user_id)->first();
Since you're checking against the user's id, you can also use find() to get one record:
User::find($profile->user_id);
You can do it some ways.
Solution 1:
User::whereId($profile->user_id)->first();
Solution 2:
User::where('id', $profile->user_id)->first();
Solution 3:
User::where('id','=', $profile->user_id)->first();
Solution 4:
User::where(['id' => $profile->user_id])->first();
Also you can do it
In Profile model define
public function user()
{
return $this->belongsTo('App\User');
}
Than you can lazy load
$user = $profile->load('user')->user; // but it is lazy loading
I have used my own custom login without using auth. Here is my code
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if($user == null){
echo "Failed"; die;
}
if($user->exists() && $isPasswordCorrect){
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
This is my login function. But its not working. When the credentials is right it redirects to dashboard i.e that's correct, but when the email or password or other credentials is wrong it showing error message. But when if the user enter such data which is not in the database then it must show message that user doesn't exists. but its going to page not found error...
I want to have the solution of this problem.
Okay, first confirm that, you have a route like '/user' defined in your web.php
You haven't used get() in $user eloquent
$user = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->get();
And it shows 404 not found error because you have used firstorFail() it will fail on no record matching and will show 404 not found error so
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->first();
if(empty($user1))
{
echo "user doesn't exists";exit;
}
As per my understanding the query $user and $user1 is same so my suggestion would be to use only one
I made the following corrections:
$data = $request; is sufficient, you don't need to do $data = $request->input();
Check the count on the Eloquent query like this count($users->get()), to check if user was found.
public function userLogin(Request $request){
if($request->isMethod('post')){
$data = $request->input();
$this->validate($request, [
'uemail'=> 'required|email',
'user_type'=> 'required',
'user_id' => 'required',
'upassword' => 'required|min:6',
],
[
'uemail.email' => 'Email must be valid',
'uemail.required' => 'Email is required',
'user_type.required' => 'Type is required',
'user_id.required' => 'Name is required',
'upassword.required' => 'Password is required',
'upassword.min' => 'Password must be at least 6 characters',
]);
$user_type = $data['user_type'];
$user_id = $data['user_id'];
$uemail = $data['uemail'];
$upassword = $data['upassword'];
$hashPass = bcrypt($upassword);
DB::enableQueryLog();
$user1 = User::where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null)->firstOrFail();
$users = DB::table('users')->where('type',$user_type)->where('user_id',$user_id)->where('email',$uemail)
->where('status',1)->where('deleted_at',null);
// $query = DB::getQueryLog();
// $query = end($query);
$isPasswordCorrect = Hash::check($upassword, $user1->password);
if(count($users->get()) == 1){
$user1 = $users->first();
$isPasswordCorrect = Hash::check($upassword, $user1->password);
echo "Success"; die;
Session::put('userSession',$user1->email);
Session::put('loginSession',$user_type);
Session::put('idSession',$user1->user_id);
return redirect('/user/dashboard');
} else {
return redirect('/user')->>with('flash_message_error','Invalid Login Credentials..');
}
}
return view('death_notice.user_login');
}
I have not tested the code, but the idea should be clear.
Use following code to custom login. it's for, Ajax login, you can modify according to your requirements.
function userLogin(Request $request)
{
$auth = false;
$credentials = $request->only('email', 'password');
// if user login credentials are correct then users logged in
if (Auth::attempt($credentials, $request->has('remember')))
{
$auth = true; // Success
}
// returns json response if login credentials are correct.
if ($auth == true)
{
return response()->json([
'auth' => $auth,
'intended' => URL::previous(),
'msg'=>1,
'name' => Auth::user()->name
]);
} else { // returns json response if login credentials are incorrect
return response()->json(['msg' => 2]);
}
}
I need to insert data and update a table row in one method in My Controller using Laravel 5.2. My table name is "permission". Here is My method:
public function addPermission(Request $request, $id, Permission $permission)
{
if ($permission = Permission::findOrFail($id));{
$this->validate($request, [
'status' => 'required'
]);
$permission = new Permission;
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$values = $request->all();
$permission->fill($values)->save();
return redirect()->back()->with('info','Permission has been updated to your Collaborator successfully');
}
else {
$this->validate($request, [
'status' => 'required'
]);
$permission = new Permission;
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info','Permission has been added to your Collaborator successfully');
}
}
I get the following error
syntax error, unexpected 'else' (T_ELSE)
What am I doing wrong?
For syntax Erorr
if ($permission = Permission::findOrFail($id)); { ......
Just remove ";"
if ($permission = Permission::findOrFail($id)) { .....