I'm trying to redirect the user to a 'dashboard' page after he has registered. However, when I dump and die the auth()-user(), it returns null. It should display the information of the authenticated user from my database.
Register Controller
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RegisterController extends Controller
{
public function NavRegPage(){
return view('regPage');
}
public function store(Request $request){
$data = request()->validate([
'username' => ['required', 'max:20'],
'password' => ['required', 'min:5', 'max:20' ],
'email' => ['required', 'email'],
'url' => ['required', 'url'],
'dob' => ['required']
]);
$user = new User();
$user->username = request('username');
$user->password = request('password');
$user->email = request('email');
$user->url = request('url');
$user->dob = request('dob');
$user->save();
auth()->attempt($request->only('email', 'password'));
return redirect()->route('dash');
}
Dash controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashController extends Controller
{
public function index(){
dd(auth()->user());
}
}
Web.php
use App\Http\Controllers\RegisterController as RegisterController;
use App\Http\Controllers\DashController as DashController;
use Illuminate\Support\Facades\Route;
Route::get('/register', [RegisterController::class, 'NavRegPage']) ->name('register');
Route::get('dash', [\App\Http\Controllers\DashController::class, 'index']) ->name('dash');
Route::get('/', function () {
return view('index');
});
Route::post('/register', [RegisterController::class, 'store'])->name('register');
I want the dd to show me the authenticated user information so I can continue with my work.
Thank you
in web.php
Route::get('dash', [\App\Http\Controllers\DashController::class, 'index']) ->name('dash')->middleware('auth');
apply ->middleware('auth'); then your auth() will work on that controller
Related
I'm trying to make a register page with role as a radio button(consumer, supplier, Admin)
but it show me this error when I test the query in postman
Error: Class "App\Http\Models\Role" not found in file
my controller:
public function register(Request $request)
{
$request->validate([
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|string|unique:users',
'password'=>'required|string|min:6',
'phone_number'=>'required|string|min:10',
'role_name'=>'required|string'
]);
$role_a = $request->role_name;
if ($role_a == 'صاحب متجر'){
$role=Role::select('role_id')->where('role_name','صاحب متجر')->first();
$user->roles()->attach($role);
return response()->json($user);
}
elseif ($role_a == 'مشتري'){
$role=Role::select('role_id')->where('role_name','مشتري')->first();
$user->roles()->attach($role);
return response()->json($user);
}
$user=User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone_number' => $request->phone_number,
]);
And my use statement:
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Role;
use Illuminate\Support\Facades\Hash;
And my route:
Route::post('/register','App\Http\Controllers\AuthController#register');
and this what I have in tables:
Note: I didn't use custom packages like spatie for example
Thank you for trying to help!
You miss adding the Request class as an argument into your method. Your method should look like this:
public function register(Request $request)
{
//after validation
$data = $request->validated();
}
Dont forget to add use Illuminate\Http\Request; in your use statement.
My register method of the RegisterController:
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
If I go through this flow the user is authenticated and the event is fired, but the user is not redirected... Now for the confusing part: if I move the redirect line above the event line, it does work (but obviously the event doesn't fire):
Auth::login($user);
return redirect()->route('account.index'); // User is correctly redirected here
event(new Registered($user));
What's happening here?
Full RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function showRegistrationForm()
{
return view('auth.register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::login($user);
event(new Registered($user));
return redirect()->route('account.index');
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data, array $ua)
{
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
]);
return $user;
}
}
Try to authenticate user with id :
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
Auth::loginUsingId($user->id);
event(new Registered($user));
return redirect()->route('account.index');
}
I can't understand what is happening here. on my local server its working fine but when I put everything on my live server I'm having this error
My web Route
Auth::routes(['verify' => true]);
Route::get('/', function(){
return view('auth.login');
})->name('auth.login')->middleware('auth');
Route::resource('/register', 'Auth\registerController#index')->name('register');
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['namespace' => 'dashboard', 'prefix' => 'dashboard'], function() {
Route::get('/', 'DashboardController#index');
});
SO ON...
}
My RegisterController
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
public function index(Request $request)
{
$referral = '';
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if (is_null($keyword))
return view ( 'Auth.register');
elseif ($referral)
return view ( 'Auth.register', compact('referral', $referral))
->withDetails ( $referral )
->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not existing or already been taken.' );
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'country_code' => $data['country_code'],
'phone_number' => $data['phone_number'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
registerController Path
what do you this causing this?
Thank you in advance!
this line of code in your web.php file is causing the issue
Route::resource('/register', 'Auth\registerController#index')->name('register');
your class name starts with R but you have written using r. moreover it seems the route is a simple get route but you have written it as resource. change this too. so the route should be like
Route::get('register', 'Auth\RegisterController#index')->name('register');
How did you namespace your registerController?
Because laravel later versions use a rather different namespace than previous versions. Hence change your namespace (and imported files) to this;
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
If you are using laravel 8:
use App\Http\Controllers\Auth\RegisterController;
Auth::routes(['register' => false]);
Route::get('/user_register', [RegisterController::class, 'showRegistrationForm'])->name('register');
However it throws this error when I clean cache:
Unable to prepare route [user_register] for serialization. Another route has already been assigned name [register].
The new route works, but the old route yet it works
I have installed socialite package in my application but its not working properly.
In my login with linkedin button i have given url like below
href="{{ url('auth/linkedin') }}"
My route file is
Route::get('auth/linkedin', 'LinkedInController#redirectToLinkedin');
Route::get('/linkedin/callback', 'LinkedInController#handleLinkedinCallback');
LinkedInController.php is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Auth;
use Socialite;
use Exception;
class LinkedInController extends Controller {
protected $redirectTo = '/';
//use Illuminate\Foundation\Auth\AuthenticatesUsers;
public function __construct()
{
//$this->middleware('guest', ['except' => 'logout']);
}
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) {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function redirectToLinkedin() {
return Socialite::driver('linkedin')->redirect();
}
public function handleLinkedinCallback() {
try {
$user = Socialite::driver('linkedin')->user();
$create['name'] = $user->name;
$create['email'] = $user->email;
$create['linkedin_id'] = $user->id;
$userModel = new User;
$createdUser = $userModel->addNew($create);
Auth::loginUsingId($createdUser->id);
return redirect('/index');
} catch (Exception $e) {
return redirect('auth/linkedin');
}
}
}
After i clicking login with linkedin it will comes to redirectToLinkedin() function but i got error like
This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
Whats a problem with my code?
I am implementing a registration form using JSON post request and laravel 5.3 with the below Controller settings
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
$data = $data['Register'];
$validator = Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
if($validator->fails())
{
$errors = $validator->errors()->all()[0];
//dd($errors);
return response()->json(['errors'=>$errors]);
}
else
{
return $validator;
}
}
protected function create(array $data)
{
$data = $data['Register'];
//dd($data);
User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
return response()->json(['success' => $data['email']], 200);
}
}
But i want to track server errors in the event of multiple registration with the same email. I have handled this on the client side but in need to handle on the backend too.
The Problem is with the validator function it keep returning below error
FatalThrowableError in RegistersUsers.php line 31:
Call to undefined method Illuminate\Http\JsonResponse::validate()
I have checked inside the framework code and there is a validate method which seems to be unrecognized with the json response any ideas?