Created
February 28, 2020 14:19
-
-
Save godilite/d111b681b093c2eed451f28d0bcd61e3 to your computer and use it in GitHub Desktop.
Login, Register and Logout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Auth; | |
use App\User; | |
use Illuminate\Support\Facades\Hash; | |
use Illuminate\Support\Facades\Validator; | |
class UserController extends Controller | |
{ | |
public function register(Request $request) | |
{ | |
$this->validator($request->all())->validate(); | |
$user = $this->create($request->all()); | |
$this->guard()->login($user); | |
return response()->json(['user'=> $user, | |
'message'=> 'registration successful' | |
], 200); | |
} | |
/** | |
* Get a validator for an incoming registration request. | |
* | |
* @param array $data | |
* @return \Illuminate\Contracts\Validation\Validator | |
*/ | |
protected function validator(array $data) | |
{ | |
return Validator::make($data, [ | |
'name' => ['required', 'string', 'max:255'], | |
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], | |
'password' => ['required', 'string', 'min:4', 'confirmed'], | |
]); | |
} | |
/** | |
* Create a new user instance after a valid registration. | |
* | |
* @param array $data | |
* @return \App\User | |
*/ | |
protected function create(array $data) | |
{ | |
return User::create([ | |
'name' => $data['name'], | |
'email' => $data['email'], | |
'password' => Hash::make($data['password']), | |
]); | |
} | |
protected function guard() | |
{ | |
return Auth::guard(); | |
} | |
public function login(Request $request) | |
{ | |
$credentials = $request->only('email', 'password'); | |
if (Auth::attempt($credentials)) { | |
// Authentication passed... | |
return response()->json(['message' => 'Login successful'], 200); | |
} | |
} | |
public function logout() | |
{ | |
Auth::logout(); | |
return response()->json(['message' => 'Logged Out'], 200); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment