1# Database Preparation
2// add api_token to users table
3Schema::table('users', function ($table) {
4 $table->string('api_token', 80)->after('password')
5 ->unique()
6 ->nullable()
7 ->default(null);
8});
9
10// Create token for existing users, code can also be added to registerController
11 $token = Str::random(60);
12 $user = User::find(1);
13 $user->api_token = hash('sha256', $token); // <- This will be used in client access
14 $user->save();
15
16
17
18//config/auth.php
19 'guards' => [
20 'web' => [
21 'driver' => 'session',
22 'provider' => 'users',
23 ],
24
25 'api' => [
26 'driver' => 'token', // <- Add this entry
27 'provider' => 'users',
28 'hash' => false,
29 ],
30 ],
31
32
33
34//routes/api.php
35 // Add "middleware('auth:api')" as below
36 Route::middleware('auth:api')->get('/user', function (Request $request) {
37 return $request->user();
38 });
39
40
41
42//client access example (in Vue js)
43
44axios.get('http://example.com/api/user',
45 {
46 headers: {
47 'Accept': 'application/json',
48 'Authorization': 'Bearer '+ 'user-api-token'
49 }
50}
51 )
52 .then(function (response) {
53 // handle success
54 console.log(response);
55})
56 .catch(function (error) {
57 // handle error
58 console.log(error);
59})
60
61