1/**
2 * API Register
3 *
4 * @param Request $request
5 * @return \Illuminate\Http\JsonResponse
6 */
7public function register(Request $request)
8{
9 $rules = [
10 'name' => 'unique:users|required',
11 'email' => 'unique:users|required',
12 'password' => 'required',
13 ];
14
15 $input = $request->only('name', 'email','password');
16 $validator = Validator::make($input, $rules);
17
18 if ($validator->fails()) {
19 return response()->json(['success' => false, 'error' => $validator->messages()]);
20 }
21 $name = $request->name;
22 $email = $request->email;
23 $password = $request->password;
24 $user = User::create(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]);
25
26}
27
1<?php
2
3namespace App\Http\Controllers;
4
5
6use Illuminate\Http\Request;
7use App\User;
8
9class AuthController extends Controller
10{
11 public $loginAfterSignUp = true;
12
13 public function register(Request $request)
14 {
15 $user = User::create([
16 'name' => $request->name,
17 'email' => $request->email,
18 'password' => bcrypt($request->password),
19 ]);
20
21 $token = auth()->login($user);
22
23 return $this->respondWithToken($token);
24 }
25
26 public function login(Request $request)
27 {
28 $credentials = $request->only(['email', 'password']);
29
30 if (!$token = auth()->attempt($credentials)) {
31 return response()->json(['error' => 'Unauthorized'], 401);
32 }
33
34 return $this->respondWithToken($token);
35 }
36 public function getAuthUser(Request $request)
37 {
38 return response()->json(auth()->user());
39 }
40 public function logout()
41 {
42 auth()->logout();
43 return response()->json(['message'=>'Successfully logged out']);
44 }
45 protected function respondWithToken($token)
46 {
47 return response()->json([
48 'access_token' => $token,
49 'token_type' => 'bearer',
50 'expires_in' => auth()->factory()->getTTL() * 60
51 ]);
52 }
53
54}
55
56