Undefined array key "email" - php

I can't seems to find the reason why it gives me the error Undefined array key "email"
I'm sorry in advance if the info that I'm providing is not enough please tell me what info you guys need.
here is my admin controller
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function dashboard()
{
return view('admin.dashboard');
}
public function login(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
// echo "<pre>";
// print_r($data);
// die;
if (Auth::guard('admin')->attempt(['email' => $data['email'], 'password' => $data['password'], 'status' => 1])) {
return redirect('admin/dashboard');
} else {
return redirect()->back()->with('error_message', 'Invalid Email or Password');
}
}
return view('admin.login');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use HasFactory;
protected $guard = 'admin';
}
I already try changing the ['email' => $data['email'] to $data['email'] = 'example#example.com'
but it just give me the error that i have to migrate again which i'm not aiming for, should i migrate?

Related

cannot use my model on my controller " Undefined type 'App\Usuario' " Laravel

Hello I cannot use my model inside controller Undefined type 'App\Usuario' on Laravel.
When I try to, create, edit or remove an user I am getting error Undefined type 'App\Usuario' appears.
A few days ago the code worked for me but when I made another model called "paintings" they both stopped working. Maybe has some relation.
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Usuario extends Model
{
use Notifiable;
use HasFactory;
// ...
}
namespace App\Http\Controllers;
use App\Usuario;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
class UsuariosController extends Controller
{
public function index()
{
$usuarios = DB::table('usuarios')
->select('usuarios.*')
->orderBy('id', 'DESC')
->get();
return view('usuarios')->with('usuarios', $usuarios);
}
public function store(Request $request)
{
$id = 0;
// Validation ...
$usuario = Usuario::create([
'id' => $request->id,
'nombre' => $request->nombre,
'email' => $request->email,
'contrasena1' => Hash::make($request->contrasena1),
'contrasena2' => $request->contrasena2,
]);
return back()->with('UsuarioAgregado', 'Usuario agregado con éxito');
}
public function destroy($id)
{
$usuario = Usuario::find($id);
$usuario->delete();
return back()->with("El ususario se elimino correctamente");
}
public function editarUsuario(Request $request)
{
$usuario = Usuario::find($request->id);
// Validation ...
$usuario->nombre = $request->nombre;
$usuario->email = $request->email;
$validator2 = Validator::make($request->all(), [
'contrasena1' => 'required|min:7|required_with::contrasena2|same:contrasena2',
'contrasena2' => 'required|min:7'
]);
if (!$validator2->fails()) {
$usuario->contrasena1 = Hash::make($request->contrasena1);
}
$usuario->save();
return back()->with("El usuario se actualizo correctamente");
}
}
Sorry if my English is not good.
[1]: https://i.stack.imgur.com/MCKnl.png
Assuming that the class Usuario is located in the folder App this can be a Laravel 5 project.
the top of your model needs the namespace line
<?php
namespace App;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Usuario extends Model
maybe you need to use this code on the header of your controller :
use App\Models\Usuario;
that's a common problem. it depends on the structure of your project's directory.

i am getting error when i am fetching user data from database in laravel through API

Hello Guys nowadays am working on laravel api everything is perfect just one issue am facing that is when i write wrong username and password so i am able to get user data but when i enter correct user information so i am getting exception that is invalid credentials. please help me
here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class email extends Model
{
protected $table = 'users';
}
&
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\email;
class EmailController extends Controller
{
public function databyemail(Request $request){
$data = email::where('email', $request->email)->first();
if($data->password === bcrypt($request->password))
{
return response()->json($data);
}
else
{
return response()->json(['error' => 'Incorrect credentials!']);
}
}
}
Can you try Hash::check method for matching password.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Hash;
use App\email;
class EmailController extends Controller
{
public function databyemail(Request $request){
$data = email::where('email', $request->email)->first();
if( Hash::check( $request->password, $data->password ) ) {
return response()->json($data);
}else{
return response()->json(['error' => 'Incorrect credentials!']);
}
}
}

Laravel - Auth::user data return null except Login Controller

I am creating user authentication using a custom table. In my login controller authentication is working fine and redirected to dashboard. But when I am going to create another url using a new controller, user auth data not showing for that controller.
I want to get user data through auth facade in constructor. How will that possible?
Here is my code:
web.php:
<!---Routes for login and dashboard-->
Route::get('/login','CustomLogin#index');
Route::post('/login','CustomLogin#checklogin');
Route::get('/','CustomLogin#SuccessLogin');
Route::get('/logout','CustomLogin#logout');
<!---Routes for other controller where user auth not working-->
Route::get('/add-creditor', 'AddCreditor#index');
CustomLogin.php (controller):
<?php
namespace App\Http\Controllers;
use App\library\My_functions;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Auth;
use Redirect;
use View;
use Session;
use Cookie;
class CustomLogin extends Controller
{
public function __construct()
{
$this->_myFun = new My_functions;
}
public function index()
{
if(!Auth::check()) {
return view('CustomLogin.CustomLogin');
}
else{
Redirect::to(SITE_URL)->send();
}
}
public function username()
{
return 'user_name';
}
function checklogin(Request $request)
{
$this->validate($request, [
'input-username' => 'required',
'input-password' => 'required'
]);
$user_data = array(
'user_name' => $request->get('input-username'),
'password' => $request->get('input-password')
);
if(Auth::attempt($user_data)){
return redirect('/');
}
else
{
return back()->with('error','Wrong Login Details');
}
}
function SuccessLogin(){
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
else {
$data=array();
return View::make('include.dashboard',$data);
}
}
function logout(Request $request){
Auth::logout();
return redirect('/login');
}
}
Function DoLogIn() (app/library)
<?php namespace App\library {
use Illuminate\Routing\Controller as BaseController;
use App\library\CreateCrmGuid; // Get custom function
use App\library\FunctionForContact; // Get custom function
use Illuminate\Http\Request;
use Session;
use DB;
use Hash;
use Auth;
use App\User;
class My_functions{
public function DoLogIn()
{
//dd(Auth::user()); /*returns data if run from Login controller but null from Add Creditor controller*/
if(Auth::check())
{
$user_id = Auth::user()->id;
define('authenticated_user_id' ,$user_id);
return true;
}
else
{
return false;
}
}
}
AddCreditor Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Cookie;
use Config;
use App\library\my_functions; // Get custom function
use Redirect;
use DB;
use Session;
class AddCreditor extends Controller
{
protected $_myFun;
function __construct(){
dd(Auth::user()); // this returns null
$this->_myFun = new My_functions;
if (!$this->_myFun->DoLogIn()) {
Redirect::to(SITE_URL.'login')->send();
}
}
}
Add auth Middleware in your routes
Route::middleware(['auth'])->get('/add-creditor', 'AddCreditor#index');
Still, after this, you might not get user data through Auth facade in the controller constructor, But in your Route method i.e. AddCreditor#index you will get the user data either through the following methods
Auth::user();
or
request()->user();

Laravel 5.6: Auth::check() fails directly after successful Auth::login

I am using version 5.6 of Laravel.
I try to manually write a login controller which on success leads to the dashboard and on fail back to the login.
The problem is when i try to login the MainController allways redirects back to the login. So i checked if the user got logged in properly in the LoginController by checking if Auth::check works afer logging in and found out that it fails which makes it seem like for some reason the user doesn't get logged in properly even though i don't get any error messages.
I searched for hours and tried many things to fix this issue but with no success. So i hope someone can give me a pointer to how to solve this problem.
My setup looks like this:
web.php
<?php
Route::get('/', 'MainController')->name('dashboard');
Route::get('/login', 'LoginController')->name('login');
Route::post('/login/authenticate', 'LoginController#authenticate')->name('authenticate');
MainController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class MainController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function __invoke()
{
return view('maintenance');
}
}
LoginController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
class LoginController extends Controller
{
$user = User::where('userid', $request->input('username'))
->where('user_pass', $request->input('password'))
->where('state', 0)
->first();
if($user) {
Auth::login($user);
if (Auth::check()) {
dd('Auth::check() failed');
}
//return redirect()->route('dashboard');
} else {
return redirect()->back()->withInput();
}
}
}
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $primaryKey = 'account_id';
protected $table = 'login';
public $timestamps = false;
}
if (Auth::check()) {
dd('Auth::check() failed');
}
User is logged in when Auth::check() returns true.
So other way around as it is in your code. Eg:
if (!Auth::check()) {
dd('Auth::check() failed');
}
You can try this code:
if (Hash::check('plain-text', $hashedPassword)) {
// The passwords match...
}
Try to use like that
public function store()
{
$credentials = array('user_displayname'=>Input::get('user_displayname'),
'user_password'=> Input::get('user_password'));
if (Auth::attempt($credentials))
{
return Auth::user();
}
return 'not logged';
}

Class App\Http\Controllers\Auth\Request does not exist. Laravel 5.3

I am using Laravel 5.3 My ForgotPasswordController looks like that:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
class ForgotPasswordController extends BaseController
{
use SendsPasswordResetEmails;
public function __construct()
{
$this->middleware('guest');
}
public function showLinkRequestForm()
{
$title = $this->title;
$appName = $this->appName;
$action = $this->action;
return view('password.forgotPassword')->with(compact('title', 'appName', 'action'));
}
}
ResetPasswordController code :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Base\BaseController;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends BaseController
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('passwords.resetPassword')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, [
'token' => 'required',
'password' => 'required|confirmed|min:6',
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
}
My Admin Route :
Route::group(['namespace' => 'Auth'], function() {
Route::get('/forgotpassword/reset', 'ForgotPasswordController#showLinkRequestForm');
Route::post('/forgotpassword/email', 'ForgotPasswordController#sendResetLinkEmail');
Route::get('/password/reset/{token}', 'ResetPasswordController#showResetForm');
Route::post('/password/reset', 'ResetPasswordController#reset');
});
BaseController Code :
<?php
namespace App\Http\Controllers\Base;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
protected $appName = 'Stackoverflow';
protected $title = 'Welcome to Stackoverflow';
protected $action;
}
I can send the link to my email, but once I click the link/button.
It throws an error like above. Any idea ?
You are not using the required namespace, try to use the following in your controller:
use Illuminate\Http\Request;
You are getting the error due to the fact that your script tries to load the Request class from the current namespace :App\Http\Controllers\Auth
Request docs for Laravel 5.3

Categories