I'm getting below error when trying login with google or Facebook.
Argument 1 passed to Illuminate\Auth\Guard::login() must implement
interface Illuminate\Contracts\Auth\Authenticatable, null given
i'm using socialite package for laravel. what is the problem, i'm unable to solve it.i'm first time using laravel Socialite package
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Laravel\Socialite\Facades\Socialite;
class RegisterController extends Controller
{
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'user_type' => 'user',
'active_status' => '1'
]);
}
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallback()
{
try{
$socialuser = Socialite::driver('facebook')->stateless()->user();
}
catch(exception $e){
return redirect('/');
}
$user=User::where('facebook_id',$socialuser->getid())->first();
if(!$user)
User::create([
'facebook_id'=>$socialuser->getid(),
'email'=>$socialuser->getemail(),
'name'=>$socialuser->getname(),
]);
auth()->login($user);
return redirect()->to('/dashboard');
}
}
Please help me.i'm a beginner.
Thanks
Check your User model make sure it implements Authenticable. I'd guess it currently extends Model but doesn't use Authenticable. Post it here to let use confirm it looks ok.
Related
How to integrate laravel throttle if I did not use the default LoginController given by laravel?
here's my controller:
use AuthenticatesUsers;
//function for login
public function login(Request $requests){
$username = $requests->username;
$password = $requests->password;
/**to login using email or username**/
if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
Auth::attempt(['email' => $username, 'password' => $password]);
} else {
Auth::attempt(['username' => $username, 'password' => $password]);
}
if(Auth::check()){
if(Auth::user()->type_user == 0){
return view('users.dashboard');
}
else{
return view('admin.dashboard');
}
}
else{
return Redirect::back()->withInput()->withErrors(['message'=>$login_error],'login');
}
}
I want to limit the failed logins but I can't seem to make it work using my own controller. Can you guys help me please?
add the following code inside your method. make it the first thing
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
now add the following code where log in fails. this will increment the failed attempt count.
$this->incrementLoginAttempts($request);
on successful login, add the following code so it resets.
$this->clearLoginAttempts($request);
Try adding throttling to your controller's constructor, like so:
/**
* Create a new login controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('throttle:3,1')->only('login');
}
Unfortunately, the Laravel docs don't say much about throttling:
https://laravel.com/docs/6.x/authentication#login-throttling
However, the 3,1 part of the string corresponds to a maximum of 3 tries with a decay time of 1 minute.
throttle could be defined in /project-root/laravel/app/Http/Kernel.php in the routeMiddleware array like so:
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,.
The Laravel documentation explains this method here: https://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes
use Trait ThrottlesLogins present in Illuminate\Foundation\Auth and override the 2 functions as mentioned below. I have tested it on Laravel 5.6 and working fine.
public function maxAttempts()
{
//Lock out on 5th Login Attempt
return 5;
}
public function decayMinutes()
{
//Lock for 1 minute
return 1;
}
Although, this answer is very late, but here is , what i did, and it worked. I hope it helps you too. I am using laravel 5.2.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\MessageBag;
use Cookie;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UserController extends Controller
{
/** Add This line on top */
use AuthenticatesAndRegistersUsers,ThrottlesLogins;
/** This way, you can control the throttling */
protected $maxLoginAttempts=3;
protected $lockoutTime=300;
public function postUserSignIn(Request $request)
{
/** This line should be in the start of method */
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
/** Validate the input */
$validation = $this->validate($request,[
'email' => 'required|email',
'password' => 'required|min:4'
]);
/** Validation is done, now login user */
//else to user profile
$check = Auth::attempt(['email' => $request['email'],'password' => $request['password']]);
if($check){
$user = Auth::user();
/** Since Authentication is done, Use it here */
$this->clearLoginAttempts($request);
if ($user->role == 1 || $user->role == 2){
if(Session::has('cart')){
return redirect()->route('cart');
}
return redirect()->intended();
}elseif($user->role == 99) {
return redirect()->route('dashboard');
}
}else{
/** Authentication Failed */
$this->incrementLoginAttempts($request);
$errors = new MessageBag(['password' => ['Email and/or Password is invalid']]);
return redirect()->back()->withErrors($errors);
}
}
}
Route::post('login', ['before' => 'throttle:2,60', 'uses' => 'YourLoginController#Login']);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return redirect()->route('login')->with('alert-warning', 'Too many login attempts');
}
protected function hasTooManyLoginAttempts(Request $request)
{
$maxLoginAttempts = 3;
$lockoutTime = 1; // In minutes
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request), $maxLoginAttempts, $lockoutTime
);
}
try my version:
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller{
use AuthenticatesUsers;
public function login(Request $request){
if($this->hasTooManyLoginAttempts($request)){
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}else{
if (Auth::attempt(['username' => $request->login_username, 'password' => $request->login_password])) {
session()->put(['username'=>Auth::user()->username,'userid'=>Auth::user()->id]);
return redirect()->intended('anydashboard');
}else{
$this->incrementLoginAttempts($request);
//my '/' path is the login page, with customized response msg...
return redirect('/')->with(['illegal'=>'Login failed, please try again!'])->withInput($request->except('password'));
}
}
}
}
in order to use Eloquent Model Auth (which is default), your AUTH_MODEL should implements AuthenticatableContract, so double check your model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract,CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
//protected $fillable = [];
...
}
Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class invitacionController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
return view('administrar');
}
public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);
/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);
return redirect('/administrar');
}
}
If the relationship is properly configured, the first (commented) method should be working.
As for the second method, I think you are adding extra brackets:
DB::table('invites')->insert([
'usuId' => $request->user()->id, // <---
'code' => str_random(40),
'email' => $request->input('email')
]);
That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:
return $this->hasMany('App\Comment', 'foreign_key');
So I think you should do
public function invites()
{
return $this->hasMany(Invite::class, 'usuId');
}
Hey guys I'm trying to learn PHP frameworks as well as OOP and I'm using Laravel 5.1 LTS.
I have the following code in my AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\Verification;
use Mail;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data){
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// generate our UUID confirmation_code
mt_srand((double)microtime()*15000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$uuid = substr($charid, 0, 8)
.substr($charid, 8, 4)
.substr($charid,12, 4)
.substr($charid,16, 4)
.substr($charid,20,12);
$data['confirmation_code'] = $uuid;
// pass everything to the model here
$setVerification = new Verification();
$setVerification->setVerificationCode($data['email'], $data['confirmation_code']);
// send email for confirmation
Mail::send('email.test', $data, function ($m) use ($data){
$m->from('test#test.com', 'Your Application');
$m->to($data['email'])->subject('Thanks for register! Dont forget to confirm your email address');
});
return $user;
}
}
my error message Class 'Models\Verification' not found is coming from this piece of code here
// pass everything to the model here
$setVerification = new Verification();
$setVerification->setVerificationCode($data['email'], $data['confirmation_code']);
which looks right to my beginner's eyes, but it's clearly wrong.
Here is my Verification class that has the setVerificationCode method
<?php
namespace App\Http\Controllers;
use App\User;
use DB;
use App\Http\Controllers\Controller;
class Verification {
/**
* This method will update the confirmation_code column with the UUID
* return boolean
**/
protected function setVerificationCode($email, $uuid) {
$this->email = $email;
$this->uuid = $uuid;
// check to see if $email & $uuid is set
if (isset($email) && isset($uuid)) {
DB::table('users')
->where('email', $email)
->update(['confirmation_code' => $uuid]);
return TRUE;
} else {
return FALSE;
}
}
/**
* This method will validate if the UUID sent in the email matches with the one stored in the DB
* return boolean
**/
protected function verifyConfirmationCode() {
}
}
Please give the following in AuthController
use App\Http\Controllers\Verification;
instead of
use App\Verification;
If we give use App\Verification , it will check if there is any model named Verification.
its seems that, you are missing something, which, Extend your Model with eloquent model
use Illuminate\Database\Eloquent\Model;
class Verification extends Model
{
and the rest is seems fine.
also share your verification model code
Updated
instead of your this line
use App\Verification;
do this
use App\Models\Verification;
as you created custom directory for your Models then its better to auto load it in your composer.json file. add this line "app/Models" in your "autoload" section. follow this
"autoload": {
"classmap": [
"database",
"app/Models"
],
and after that, run this command in your project repo composer dump-autoload
I am new in laravel5 Framework. when I insert data into database using laravel5 at that time I get error like....
FatalErrorException in ClientFormRequest.php line 10:
Cannot make static method Symfony\Component\HttpFoundation\Request::create() non static in class App\Http\Requests\ClientFormRequest
my all files are below...
app/Http/Controller/RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use Illuminate\Http\Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
app/Http/Requests/ClientFormRequest.php
<?php namespace App\Http\Requests;
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
public function create(array $data)
{
return client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
Routes
Route::get('client', 'RegisterController#create');
Route::post('contact_store', 'RegisterController#store');
First of all, i would suggest you to watch Laravel 5 Fundamentals repeatedly since it is free. Other series also give great information.
Secondly, I would suggest you to use at least Sublime Text and some useful packages to be able to inspect the depth nested relations of system files (Namespaces, Interfaces, Inheritance Tree etc...). If you can't/might not, this friend will serve you anytime Laravel API
Third, AFAIK, Laravel Request is build onto the Symfony' Request Component. Since you are trying to overload one of its core function as non static, you are getting this error.
In addition, to be honest, i wouldn't put my user/client model creation logic into the requests. Laravel provides an good example for this kind of misconception. In the App\Services folder, you will find a registrar service for Laravel oem user model.
Let's inspect the problem with different cases.
but first, basic...
Lets assume that all logic should be put inside the controller.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store()
{
$data = Request::all(); //requested data via Facade
//prepare validatation
$validation = Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
// create the client
Client::create([
'fullname' => Request::input('fullname'),
'email' => Request::input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
Second Solution
You might be willing to separate the validation logic and apply some dependency injection.
RegisterController.php
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
ClientFormRequest.php
use Stringy\create;
use App\User;
use Validator;
use App\Http\Requests\ClientFormRequest;
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
return [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users'
];
}
}
Third Solution
You might be willing to take things further and even separate the object creation logic as an service to use it anywhere. Now your request file would stay the same. However,
RegisterController.php
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ClientFormRequest;
use App\Services\ClientRegistrar;
class RegisterController extends Controller {
private $registrar;
public function __construct(ClientRegistrar $registrarService)
{
$this->registrar = $registrarService;
}
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
$newClient = $this->registrar->create($request->all());
return \Redirect::route('Client.client')
->with('message', 'Record Inserted!')->compact('newClient');
}
}
App\Services\ClientRegistrar.php
use App\Client;
use Validator;
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
class ClientRegistrar implements RegistrarContract {
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
/**
* Create a new client instance after a valid registration.
*
* #param array $data
* #return Client
*/
public function create(array $data)
{
// create the client
return Client::create([
'fullname' => $data['fullname'],
'email' => $data['email'],
]);
}
}
To My Conclusion
There is no correct and best way to solve a problem. Stay with the best applicable and appropriate way for you and your project scale.
You also might be interested in;
Jeffrey Way's Laravel Auto Validate on Save
The error message tells you that you are overriding the create method in the ClientFormRequest class. So remove the method there. Instead create the new Client in your Controller.
Below I updated your classes to reflect the changes.
ClientFormRequest
class ClientFormRequest extends Request {
public function authorize()
{
return true;
}
public function rules()
{
}
public function validator(array $data)
{
return Validator::make($data, [
'fullname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
]);
}
}
RegisterController
class RegisterController extends Controller {
public function create()
{
return view('Client.client');
}
public function store(ClientFormRequest $request)
{
// ClientFormRequest was valid
// create the client
Client::create([
'fullname' => $request->input('fullname'),
'email' => $request->input('email'),
]);
return Redirect::route('Client.client')
->with('message', 'Record Inserted!');
}
}
I'm using Sentry 2.1 for authentication.
My User Model:
<?php namespace App\Models;
use Eloquent;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends \Cartalyst\Sentry\Users\Eloquent\User implements UserInterface, RemindableInterface {
/* Sentry Defaults omitted for brevity */
public function children()
{
return $this->hasMany('App\Models\Children');
}
public function getFullNameAttribute()
{
return trim($this->attributes['first_name'] . ' ' . $this->attributes['last_name']);
}
}
My login function:
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($credentials))
{
$user = Sentry::authenticate($credentials, $remember);
return Redirect::to('/');
}
The reason why I'm using Auth::attempt and then Sentry::authenticate is because I am migrating from an old database to a new one, so I attach a hook/listener on auth.attempt so I can process checking for old password.
Now, after I'm logged in, I can't access the full_name accessor attribute.
$user = Sentry::getUser();
echo $user->full_name; // results in NULL
I think I'm missing a small thing here but I just can't find that missing piece.
Thanks for the help!
did you edit config of Sentry (dir: /app/config/packages/cartalyst/sentry/config.php") ??
from
'model' => 'Cartalyst\Sentry\Users\Eloquent\User',
to
'model' => 'App\Models\User',