Class 'App\Http\Controllers\Hash' not found

I'm trying to use Hash in my global functions file.

I keep getting this error.

Class 'App\Http\Controllers\Hash' not found

where my file below is located at:

/app/Helpers/functions.php

<?php

    use App\Http\Controllers\Hash;

    // If old password matches password
    function checkOldPassword($oldPassword, $user) {
        if (Hash::check($oldPassword, $user->password)) {
            dd('a');
        }
        else {
            return back()->withErrors([
                'message' => 'Your old password is incorrect.'
            ]);
        }
    }

2 answers

  • answered 2018-03-13 21:21 Andrew Gillis

    As the error helpfully points out, there is no class App\Http\Controllers\Hash unless you created one. Remove that line your code should behave normally.

  • answered 2018-03-14 17:55 manix

    Hash is a facade. It is working in your controller because has been imported correctly: use Hash; However, in other classes or files, you need to import it as mentioned or using it without making an inclusion but backslash:

    <?php
    
    // If old password matches password
    function checkOldPassword($oldPassword, $user) {
        if (\Hash::check($oldPassword, $user->password)) {
            dd('a');
        }
        else {
            return back()->withErrors([
                'message' => 'Your old password is incorrect.'
            ]);
        }
    }
    

  • Laravel 5.7, do something before user logout

    I wanted to set the current user type field to something else before logout but the problem is, I don't know which controller or which method I should put this code at. Btw, I don't have AuthController in Laravel 5.7.

    $user = Auth::user();
    $user->type = "something";
    $user->save;
    
  • i made project in Laravel with custom loging . now session out automatically

    i have made project in Laravel with custom login . but now am facing session out problem , most of the time session out after 2 to 5 mints. thanks in advance.

  • Register by phone number only laravel

    how are you ?

    i'm new in laravel and i'm working in someone project and i want to register by phone number instate of email so m i can login by phone number only but is there any way to register by phone number only and get SMS verification after register

    so any one will help me please

    this is register controller code

        <?php
    
    namespace App\Http\Controllers\Auth;
    
    use App\Models\Auth\Role\Role;
    use App\Notifications\Auth\ConfirmEmail;
    use Illuminate\Auth\Events\Registered;
    use Illuminate\Http\Request;
    use App\Models\Auth\User\User;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Foundation\Auth\RegistersUsers;
    use Ramsey\Uuid\Uuid;
    
    class RegisterController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Register Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles the registration of new users as well as their
        | validation and creation. By default this controller uses a trait to
        | provide this functionality without requiring any additional code.
        |
        */
    
        use RegistersUsers;
    
        /**
         * Where to redirect users after registration.
         *
         * @var string
         */
        protected $redirectTo = '/';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest');
        }
    
        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        protected function validator(array $data)
        {
            $rules = [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|min:6|confirmed',
            ];
    
            if (config('auth.captcha.registration')) {
                $rules['g-recaptcha-response'] = 'required|captcha';
            }
    
            return Validator::make($data, $rules);
        }
    
        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array $data
         * @return User|\Illuminate\Database\Eloquent\Model
         */
        protected function create(array $data)
        {
            /** @var  $user User */
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
                'confirmation_code' => Uuid::uuid4(),
                'confirmed' => false
            ]);
    
            if (config('auth.users.default_role')) {
                $user->roles()->attach(Role::firstOrCreate(['name' => config('auth.users.default_role')]));
            }
    
            return $user;
        }
    
        /**
         * Handle a registration request for the application.
         *
         * @param  \Illuminate\Http\Request $request
         * @return \Illuminate\Http\Response
         */
        public function register(Request $request)
        {
            $this->validator($request->all())->validate();
    
            event(new Registered($user = $this->create($request->all())));
    
            $this->guard()->login($user);
    
            return $this->registered($request, $user)
                ?: redirect($this->redirectPath());
        }
    
        /**
         * The user has been registered.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  mixed $user
         * @return mixed
         */
        protected function registered(Request $request, $user)
        {
            if (config('auth.users.confirm_email') && !$user->confirmed) {
    
                $this->guard()->logout();
    
                $user->notify(new ConfirmEmail());
    
                return redirect(route('login'));
            }
        }
    }
    

    this is the api register controller code

    <?php
    
    namespace App\Http\Controllers\Api\Auth;
    
    use App\Http\Controllers\Controller;
    use App\Http\Requests\RegisterRequest;
    use App\Models\Auth\User\User;
    use Illuminate\Auth\Events\Registered;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Password;
    use Illuminate\Support\Facades\Validator;
    
    class RegisterController extends  Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Register Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles user registration via REST API
        |
        */
    
        /**
         * Handle a registration request for the application.
         *
         * @param  RegisterRequest  $request
         * @return \Illuminate\Http\Response
         */
        public function register(RegisterRequest $request)
        {
            $user = $this->create($request->all());
    
            // attach role
            $role = \App\Models\Auth\Role\Role::where('name', 'user')->first();
            $user->roles()->attach($role);
    
            event(new Registered($user));
    
            $token = $user->createToken('Default')->accessToken;
    
            return response()->json(["token" => $token, "user" => User::find($user->id)]);
        }
    
        /**
         * Verifies user's mobile
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function verifyMobile(Request $request)
        {
            Validator::make($request->all(), [
                'mobile_number' => 'required|string|exists:users,mobile_number'
            ])->validate();
    
            $user = User::where('mobile_number', $request->mobile_number)->first();
            $user->mobile_verified = 1;
            $user->save();
    
            $token = $user->createToken('Default')->accessToken;
    
            return response()->json(["token" => $token, "user" => $user]);
        }
    
        /**
         * Send a reset link to the given user.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
         */
        public function sendResetLinkEmail(Request $request)
        {
            Validator::make($request->all(), [
                'email' => 'required|email'
            ])->validate();
    
            // We will send the password reset link to this user. Once we have attempted
            // to send the link, we will examine the response then see the message we
            // need to show to the user. Finally, we'll send out a proper response.
            $response = Password::broker()->sendResetLink(
                $request->only('email')
            );
    
            return $response == Password::RESET_LINK_SENT
                ? response()->json(["message" => "Email Sent"])
                : response()->json(["message" => "Email Not Sent"], 400);
        }
    
        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return \App\Models\Auth\User\User
         */
        protected function create(array $data)
        {
            return User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt($data['password']),
                'mobile' => $data['mobile'],
            ]);
        }
    }
    

    and this is register request code

    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class RegisterRequest extends FormRequest
    {
        /**
         * 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()
        {
            return [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'mobile' => 'required|unique:users',
                'password' => 'required|min:6'
            ];
        }
    }
    

    and this is login controller code

    <?php
    
    namespace App\Http\Controllers\Auth;
    
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Http\Request;
    
    class LoginController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles authenticating users for the application and
        | redirecting them to your home screen. The controller uses a trait
        | to conveniently provide its functionality to your applications.
        |
        */
    
        use AuthenticatesUsers;
    
        /**
         * Where to redirect users after login.
         *
         * @var string
         */
        protected $redirectTo = '/admin';
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('guest', ['except' => 'logout']);
        }
    
        /**
         * Log the user out of the application.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function logout(Request $request)
        {
            $this->guard()->logout();
    
            /*
             * Remove the socialite session variable if exists
             */
    
            \Session::forget(config('access.socialite_session_name'));
    
            $request->session()->flush();
    
            $request->session()->regenerate();
    
            return redirect('/');
        }
    
        /**
         * Get the failed login response instance.
         *
         * @param  \Illuminate\Http\Request $request
         * @return \Illuminate\Http\RedirectResponse
         */
        protected function sendFailedLoginResponse(Request $request)
        {
            $errors = [$this->username() => __('auth.failed')];
    
            if ($request->expectsJson()) {
                return response()->json($errors, 422);
            }
    
            return redirect()->back()
                ->withInput($request->only($this->username(), 'remember'))
                ->withErrors($errors);
        }
    
        /**
         * The user has been authenticated.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  mixed $user
         * @return mixed
         */
        protected function authenticated(Request $request, $user)
        {
            $errors = [];
    
            if (config('auth.users.confirm_email') && !$user->confirmed) {
                $errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
            }
    
            if (!$user->active) {
                $errors = [$this->username() => __('auth.active')];
            }
    
            if(!$user->hasRole('administrator')) {
                $errors = [$this->username() => 'Only administrator can login'];
            }
    
            if ($errors) {
                auth()->logout();  //logout
    
                return redirect()->back()
                    ->withInput($request->only($this->username(), 'remember'))
                    ->withErrors($errors);
            }
    
            return redirect()->intended($this->redirectPath());
        }
    }
    

    and this is api login controller code

    <?php
    
    namespace App\Http\Controllers\Api\Auth;
    
    use App\Http\Controllers\Controller;
    use App\Http\Requests\LoginRequest;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    
    class LoginController extends Controller
    {
        /*
        |--------------------------------------------------------------------------
        | Login Controller
        |--------------------------------------------------------------------------
        |
        | This controller handles authenticating users via REST API
        |
        */
    
        public function authenticate(LoginRequest $request)
        {
            $username = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
    
            if (Auth::attempt([$username => $request->login, 'password' => $request->password])) {
                $user = Auth::user();
                $token = $user->createToken('Default')->accessToken;
                return response()->json(["token" => $token, "user" => $user]);
            }
            return response()->json(["error" => "Invalid Login"], 400);
        }
    }
    
  • Malformed UTF-8 characters, possibly incorrectly encoded with json data

    Getting error when I try to save json data in json field.

    From my database schema,

    $table->string('config_slug');
    $table->json('config')->nullable();
    

    From controller,

    public function store(Request $request)
    {
            $data = [];
            foreach ($request->tenure_type as $key => $value) {
                $data[utf8_encode($key)] = utf8_encode($request->tenure_type[$key]);
            }
    
            $tenure = Config::where('config_slug', 'tenure_type')->first();
            if ($tenure) {
                $tenure->config = $data;
                $tenure->save();
            } else {
                $config = new Config();
                $config->config_slug = 'tenure_type';
                $config->config = $data;
                $config->save();
            }
            return Config::where('config_slug', 'tenure_type')->first();
    }
    

    POST data,

    {"tenure_type":{"abcdemo":"abc demo"}}
    

    Error screenshot, error

  • Laravel direct auth attempt from custom form?

    I have a custom login form (slides out from the right side of the homepage) and I'm trying to directly log in from this form but it keeps redirecting to /login page. Is there a way to directly pass credentials on this form (mirrored after default /login form) to the Auth controller to be validated?