laravel 5.2 - Auth::user()->username is empty - php

If I use Auth::user()->username in a Blade file laravel returns me an empty String but Auth::user()->email is filled. I use my own AuthController and my Login,Register and Logout work perfectly but I can't get the username.
Routes.php
<?php
Route::group(['middleware' => ['web']] , function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::group(['middleware' => ['web','guest']], function () {
Route::auth();
#Sign up Routes
Route::get('/signup', function () {
return view('auth.signup');
})->name('auth.signup');
Route::post('/signup', 'AuthController#signup');
#Sign in Routes
Route::get('/signin', function () {
return view('auth.signin');
})->name('auth.signin');
Route::post('/signin', 'AuthController#signin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::auth();
#Sign out Routes
Route::get('/signout', 'AuthController#signout')->name('auth.signout');
});
And my custom Auth Controller is:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request) {
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|min:2|max:20',
'password' => 'required|min:6'
]);
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('home');
}
public function signin(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('flash-message','We can not sign you in with this data!');
}
return redirect()->route('home');
}
public function signout() {
Auth::logout();
return redirect()->route('home');
}
}
Maybe someone can help me
.
Note:
I added the username into User.php under the filled array.

Most likely you are missing username in $fillable of your User model.
The create method only accept fields coming from $fillable.

Please edit your User model like this:
protected $fillable = [
'email', 'username', 'password',
];
Only $fillable fields insert by Create method.

Related

Laravel - Auth, route is not logged

I've a problem when route call a method of Controller after login successfull.
In the new method user seems to be not logged.
I can't understand why.
Steps are: Log-in with
Route::post('login', 'UserController#login')->name('login');
and than check if user is logged with:
Route::get('check-login', 'UserController#checklogged');
Controller is this one:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Faker\Generator as Faker;
class UserController extends Controller
{
// regole per FormValidator
protected $rulesLogin = [
'email' => 'bail|required|email',
'password' => 'required',
];
// Effettuo il login
/**
* Method: POST
* #Parameters: email, password
* return: Authenticated User.
*/
public function login(Request $request)
{
//dd($request->all());
$validator = Validator::make($request->all(),$this->rulesLogin);
// login fallito
if ($validator->failed()) {
return response([
'status' => 'ko',
'message' => $validator->errors()->first(),
], 422);
}
// login errato
if (!Auth::attempt([
'email' => $request->email,
'password' => $request->password,
'status' => ['active'],
])) {
return response(
[
'status' => 'ko',
'message' => 'Invalid email or password',
], 422);
}
return (Auth::user());
}
public function checklogged()
{
return dd(Auth::id());
}
checklogged() return always false. I expect it return a user logged Id
I think the problem is u havent used web midlleware in route.If you are following HMVC pattern make sure to use web middleware like this.
Route::group([
'middleware' => ['web'],
], function () {
});
or please check your RouteServiceProvider.php file weather it has web middleware in mapWebRoutes() function
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
problem was middleware as guest.
Route::post('login', 'UserController#login')->name('login')->middleware('guest');
Try this sintaxe:
public function checklogged()
{
return dd(Auth::user()->id);
}

laravel 5.5 return redirect route not working

I'm having a strange issue with my laravel app .
I have a route defined as :
web.php
Route::get('/', ['as' => '/', 'uses' => 'LoginsController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginsController#postLogin']);
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginsController#getLogout']);
Route::get('/dashboard','DashboardController#dashboard')->name('dashboard');
});
In a controller , i'm trying to redirect to this route
LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginsController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web'))
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postLogin(Request $request)
{
$auth = Auth::guard('web')->attempt([
'username' => $request->username,
'password' => $request->password,
'active' => 1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
Where I am typing http://localhost:8000 in address bar of browser. I see.

Laravel Route Redirection Problems

I'm having problem redirecting my admin page to a Route::resource(); so that I could display my CRUD from the BookController
What am I doing wrong?
This is my AdminLoginController:
public function __construct(){
$this->middleware('guest:admin');
}
public function showLoginForm(){
return view('auth.admin-login');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('books.index'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
BookController
public function index()
{
$books = Book::orderBy('id','desc')->paginate(3);
return view('books.index')->withBooks($books);
}
web.php
Route::prefix('admin')->group(function(){
Route::get('/login','Auth\AdminLoginController#showLoginForm')>name('admin.login');
Route::post('/login','Auth\AdminLoginController#login')>name('admin.login.submit');
Route::get('/books/','BookController#index');
});
I think you should update your books route:
Route::get('/books/','BookController#index')->name('books.index');
OR
Route::group(['prefix' => 'admin'], function () {
Route::resource('/books','BookController#index');
});
and check your route name in php artisan route:list
update your code like:
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password],$request->remember)){
return redirect()->intended(route('admin.books.index'));
}
Hope this work for you!

how to auto login after successfully registered in laravel 5.4.12?

i want to make an auto login after successful registration and redirect to Edit Profile page.. I tried the following code but not working as i want
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/edit_profile';
public function __construct()
{
$this->middleware('guest');
}
public function createUser(Request $request)
{
$this->validate($request , [
'firstName' => 'required',
'lastName' => 'required',
'displayName' => 'required',
'email' => 'required |email',
'password' =>'required ',
'gender' =>'required',
'day' =>'required|max:2',
'month' =>'required|max:2',
'year' =>'required|max:4',
]);
$email=$request->input('email');
$password=$request->input('paasword');
$dob=$request->input('day').'-'.$request->input('month').'-'.$request->input('year');
$request->request->add(['dob'=>$dob]);
$request->request->add(['password'=>bcrypt($request->input('password'))]);
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::login($data);
}
}
Routes
Route::get('/', 'PageController#login');
Route::get('/home', 'HomeController#index');
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('main', 'PageController#main');
Route::get('browse', 'PageController#browse');
Route::get('pickngo', 'PageController#pickngo');
Route::get('edit_profile', 'PageController#profile');
}
Use Laravel loginUsingId($id) function by passing the user id.
$data = User::create($request->except(['_token', 'submit', 'day','month','year', 'confirm_password' ,'dayInWeek']));
Auth::loginUsingId($data->id);
just modify your auth login just like
if(Auth::login($data)) {
return redirect('/edit_profile');
}
else
{
return redirect()->back();
}
Scren from documentation.
You just need to add after login redirectTo property or method inside your LoginController.
P.S.it will work if you're using laravel's make:auth.

How to make custom auth in laravel 5.3

I'm facing problem in my Laravel 5.3 custom auth want to use my own functions or pages when I check Auth::check() it returns false.
Here is User controller:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Session;
use validatior;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$user = new User();
$user->email = $request->get("email");
$user->password = bcrypt($request->get['password']);
$user->save();
}
return redirect('signupPage');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect('users/profile');
}
dd(Auth::check());
exit;
}
}
After sign in I want to redirect at profile page but my condition is not working. My routes are:
Route::group(['prefix' => 'users'], function(){
Route::group(['middleware' => 'guest'], function(){
Route::get('/signupPage','UserController#getSignUp');
Route::post('/register',array ('as'=>'signup', 'uses' =>'UserController#postSignUp', ));
Route::get('signInPage', array('as' => 'signInPage', 'uses' => 'UserController#getSignIn'));
Route::post('/postLogin', array('as' => 'postLogin', 'uses' => 'UserController#postSignIn'));
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/profile', array('as' => 'profile', 'uses' => 'UserController#getProfile'));
Route::get('/logout', array('as'=>'logout', 'uses'=> 'UserController#logout'));
});
});
Here are some Modifications of your code
public function postSignUp(Request $request)
{
$email = $request->input('email');
$pass = $request->input('password');
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$pas = bcrypt($pass);
$user = new User();
$user->email = $email;
$user->password = $pas;
$user->save();
}
return redirect('users/signInPage');
}
Do use bcrypt while registering your User as this function is by default used by Auth Attempt function
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email= $request->input['email'];
$password= $request->input['password'];
if (Auth::attempt(['email'=>$email,'password'=>$password']))
{
return redirect('users/profile');
}
return redirect('users/signInPage')->withErrors(['failure' => 'The credentials you entered did not match our records. Try again!',]);
}
finally this will give you too many redirects error as you using default middlewares, because your logic is now differ from the default one that's why you have to write your custom middleware, for this run this command
php artisan make:middleware CutomAuth
this will create your custom middleware now write code in it by your logic and after registering in app/Http/Kernel.php as \n
'customauth' => \Illuminate\Auth\Middleware\CutomAuth::class, you are good to go

Categories