0👍
This my project last week, maybe can help u.
add this to User Model :
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasFactory,HasApiTokens;
protected $guarded = []; // like $fillable=[all]
}
Route :
Route::controller(UserController::class)->group(function(){
Route::post('/auth/signin','signin');
Route::post('/auth/signup','signup');
});
Controller :
class UserController extends Controller
{
public function signin(Request $request){
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
$user = User::whereEmail($credentials['email'])->first();
if(Auth::attempt($credentials)){
return response()->json([
'message' => 'login success',
// send token to front-end
'token' => $user->createToken("API TOKEN")->plainTextToken
], 200);
}
return response()->json([
'message' => 'wrong email or password'
], 500);
}
public function signup(Request $request){
$request = $request->validate([
'email' => 'required | email | string',
'password' => 'required'
]);
User::create([
'email' => $request['email'],
'password' => bcrypt($request['password'])
]);
return response()->json([
'message' => 'registration success',
], 201);
}
}
and finally :
in my preferences i make a folder lib and create axiosClient.js which contain :
import axios from 'axios';
export const axiosClient = axios.create({
withCredentials:true,
baseURL:'http://localhost:8000'
})
export const setTokenCSRF = (token) => axios.defaults.headers.common = `Bearer ${token}`
and import axiosClient.js in your front end and use setTokenCSRF function to set header axios with token csrf from backend and this token automatically use in every request.
this token is save in database in table personal_access_token.
and use should learn about csrf token works.
sorry for my english bad.
Source:stackexchange.com