laravel-api / app / Http / Controllers / AuthController.php
AuthController.php
Raw
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;


class AuthController extends Controller
{
    // Register the user
    public function register(Request $request){

        $validateUser = Validator::make(
            $request->all(),
            [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => 'required'
            ]
        );

        // Incorrect values
        if($validateUser->fails()) {
            return response()->json([
                'message'=>'Validation error',
                'error'=> $validateUser->errors()
            ],401);
        }

        //Correct values - Store the user and return a token
        $user = User::create([
            'name'=> $request['name'],
            'email'=> $request['email'],
            'password'=> bcrypt($request['password']),
        ]);

        $token = $user->createToken('APITOKEN')->plainTextToken;

        $response = [
            'message'=> 'User Created Successfully',
            'user' => $user,
            'token'=> $token
        ];
        return response($response, 201);        
    }

    // Login user
    public function login(Request $request){
        $validateUser = Validator::make(
            $request->all(),
            [
                'email' => ['required', 'string', 'email'],
                'password' => 'required'
            ]
        );
        // Incorrect values
        if($validateUser->fails()) {
            return response()->json([
                'message'=>'Validation error',
                'error'=> $validateUser->errors()
            ],401);
        }

        // Incorrect login
        if(!auth()->attempt($request->only('email', 'password'))){
            return response()->json([
                'message'=>"Invalid email/password"
            ],401);

        }
        // Correct login
        $user = User::where('email', $request->email)->first();
        return response()->json([
            'message' =>'User logged in',
            'token'=>$user->createToken('APITOKEN')->plainTextToken
        ],200);
    }

    // Logout user
    public function logout(Request $request){
        $request ->user()->currentAccessToken()->delete();

        $response = [
            'message'=>"User logged out"
        ];

        return response($response, 200);
    }

    // Get user name by id
    public function getUser($id){
        $user = User::find($id);

        if($user != null){
            return $user;
        } else {
            return response()->json(['user not found'], 404);
        }
    }

}