This is my controller's code, where i am using a query to find an email address from the table "user" against an email address that comes from a form. But it gives the error on the query's line "App\Http\Controllers\user".
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\usern;
use App\Models\post;
use Illuminate\Support\Facades\DB;
class homeController extends Controller{
public function userLogin(Request $request) {
$data= $request->input();
$userEmail= user::where('Email',$request->email)->first;
echo $userEmail;
}
}
Why you're using $request->input() ? What you can do to successfully create a login function is by attempting to log in through eloquent function
public function login(Request $request){
$validate = $this->validate($request, [
'email' => 'required|email|max:255',
'password' => 'required|min:5',
]);
$credentials = $request->only('email', 'password');
if (Auth::guard('admin')->attempt($credentials)) {
$session = $request->session()->regenerate();
return Redirect::route('admin.dashboard')->with('success','Login success.');
}
return back()->with('error','The provided credentials do not match our records.');
}
This will check if the user's email address is valid or not and if the credentials are not correct it'll return back with error that these credentials don't match.
Import correct class use App\Models\user; not use App\Models\usern;
and first letter of class name should be uppercase.
Related
How to set email and password to admin login using guards??
If I have to login for the 1st time in admin login portal what email and password is it going to verify with.
I tried adding record to database directly and logging in but that doesn't work.
when i try to login with email and password in the database, i get the following error
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\Admin given, called in C:\xampp\htdocs\Alumni datatable - Copy (2) - Copy\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php on line 434
AdminAuthController
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AdminAuthController extends Controller
{
public function getLogin(){
return view('admin.auth.login');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if(auth()->guard('admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])){
$user = auth()->guard('admin')->user();
if($user->is_admin == 1){
return redirect()->route('adminDashboard')->with('success','You are Logged in sucessfully.');
}
}else {
return back()->with('error','Whoops! invalid email and password.');
}
}
public function adminLogout(Request $request)
{
auth()->guard('admin')->logout();
Session::flush();
Session::put('success', 'You are logout sucessfully');
return redirect(route('adminLogin'));
}
}
you have to extends Authenticatable in your Admin Model
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
I want to assign an organization to a user but what happens in my code is that when I create a new organization and it's ID is 1, it automatically assigns itself to user ID 1 also.
This is my AssignOrgToUser controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\organizations;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AssignOrgToUserController extends Controller
{
public function assignOrg(Request $request, $id)
{
$users = User::find($id);
if(is_null($users)){
return response()->json(["message"=>"User not found!"], 404);
}
$rules=[
'organization'=>'required',
];
$validator = Validator::make($request->all(), $rules);
if($validator->fails()){
return response()->json($validator->errors(),400);
}
$data = $request->validate([
'organization'=>'required',
]);
$orgs = organizations::where('id', '=', $request->organization)->first();
if(is_null($orgs)){
return response()->json(["message"=>"Organization not found!"], 404);
}
$orgs= $users->save();
if($orgs){
return ["result"=>"ORG Added"];
}else{
return ["result"=>"ORG not Added"];
}
// $users->save([$orgs]);
// return response(['message'=>"Organization has beed added", $users]);
}
}
Organization Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class organizations extends Model
{
public $table = "organizations";
use HasFactory;
protected $guarded = [];
public function users(){
return $this->belongsTo('App\Models\User'); #if column not found indicate the column name
}
}
Any kind of help/suggestions will be greatly appreciated. Thank you!!
Replace this $orgs= $users->save(); with the below code
For update use associate method do like this (in your Case)
$orgs = Organisation::create(['someColumn' => $request->someColumn]);
$orgs->users()->associate($users);
$orgs->save();
for more https://laravel.com/docs/8.x/eloquent-relationships#inserting-and-updating-related-models
It seams like the problem came from you Request URL, you have define you Controller to receive a paramater name id with that I can presume you have define the Route like this
Route::post("/assign_organization/{id}", [AssignOrgToUserController::class, "assignOrg"]);
If the request url contain a user ID which is 1 any time you'll try to create an organization it will be attached to a user which ID is 1. as you are retrieving the user based on the id get from the URL
$user = User::find($id);
If you want to assign an organization with a different User ID, you should pass that User ID in you request body. and that won't consider the URL Body
$user = User::find($request->get("user_id"));
We are trying to setup the Facebook social connect on our Laravel application, but it seems like we have an issue on session creation.
Here is the code for the Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Facades\Socialite;
use App\Services\SocialAuthService;
class SocialAuthController extends Controller
{
public function redirect()
{
return Socialite::driver('facebook')->redirect();
}
public function callback(SocialAuthService $service)
{
$user = $service->createOrGetUser(Socialite::driver('facebook')->stateless()->user());
auth()->login($user);
return redirect()->intended('/');
}
}
And the code for the service :
<?php
namespace App\Services;
use Laravel\Socialite\Contracts\User as ProviderUser;
use Myproject\Users\User;
use Myproject\Users\SocialLogin;
class SocialAuthService
{
public function createOrGetUser(ProviderUser $providerUser)
{
$account = SocialLogin::where('provider', '=', 'facebook')
->where('provider_user_id', '=', $providerUser->getId())
->first();
if ($account) {
return $account->user;
}
$user = User::where('email', '=', $providerUser->email)->first();
if (!$user) {
$fullname = explode(' ', $providerUser->getName());
$user = User::create([
'email' => $providerUser->getEmail(),
'firstname' => $fullname[0],
'lastname' => $fullname[1],
'password' => md5(rand(1, 9999)),
]);
}
$account = new SocialLogin([
'provider_user_id' => $providerUser->getId(),
'provider' => 'facebook'
]);
$account->user()->associate($user);
$account->save();
return $user;
}
}
And finally the Model :
<?php
namespace Myproject\Users;
use Illuminate\Database\Eloquent\Model;
use Myproject\Users\User;
class SocialLogin extends Model
{
protected $table = 'social_logins';
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user()
{
return $this->belongsTo(User::class);
}
}
When we're trying to connect via Facebook, the information is correctly insert in Database, and the callback URL set on Facebook Developers correspond to what we have in our .env, so the redirection is correctly done but at the end we don't have any session created for the user.
I think the issue comes from cross-domain, here are the interesting parts of our .env file :
APP_URL=https://www.website.com
APP_DOMAIN=website.com
SESSION_DOMAIN=.website.com
CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
FACEBOOK_REDIRECT=https://www.website.com/callback/facebook
GOOGLE_REDIRECT=https://www.website.com/auth/google/callback
And our routing on web.php :
Route::domain('{subdomain}.{domain}')->middleware('locale')->group(function () {
Route::get('/callback/facebook', 'Auth\SocialAuthController#callback');
Route::get('/redirect/facebook', 'Auth\SocialAuthController#redirect');
});
I really think the issue is located on routing or SESSION_DOMAIN, but we tried to :
delete the session domain
routing outside the middleware locale, in a middleware auth
It still doesn't affect the login.
I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration
I'm trying to manually auth my user like this :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
use Log;
use Hash;
class UsersController extends Controller
{
public function authenticate(Request $request){
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return response()->json(User::find($email));
}
return response()->json(null);
}
}
I verify my request data, my database data, all is ok. I've also done a Hash::check with my user password and my request password, all is ok.
But the attempt always returning false.
Thanks !
Finally, I found it.
This was because I was attending a result but
return response()->json(User::find($email));
didn't find a user. So I change it for the following
return response()->json(User::where('email', $email)->first());
Thanks !