Hello, I'm new to Laravel and I need help. I have a problem with my authcontroller, what happens is that I am working with Laravel-permission, but when I call the hasRole and createToken functions VScode marks them as undefined functions. I need help please becacuse I'm just starting with Laravel. This is my auth controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request)
{
$response = ["success" => false];
//validacion
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
$response = ["error" => $validator->errors()];
return response()->json($response, 200);
}
$input = $request->all();
$input["password"] = bcrypt($input['password']);
$user = User::create($input);
$user->assignRole('tecnicologistico');
$response["success"] = true;
$response["token"] = $user->createToken("TOKEN")->plainTextToken;
return response()->json($response, 200);
}
public function login(Request $request)
{
$response = ["success" => false];
//validacion
$validator = Validator::make($request->all(), [
// 'name' => 'required',
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
$response = ["error" => $validator->errors()];
return response()->json($response, 200);
}
if (auth()->attempt(['email' => $request->email, 'password' => $request->password])) {
$user = auth()->user();
$user->hasRole('admin');
$response["token"] = $user->createToken("TOKEN")->plainTextToken;
$response['user'] = $user;
$response['success'] = true;
}
return response()->json($response, 200);
}
public function logout()
{
$response = ["success"=>false];
// Revoke token
auth()->user()->tokens()->delete();
$response = [
"success"=>true,
"message"=>"Sesión cerrada"
];
return response()->json($response, 200);
}
}
Top comments (2)
You may not use
use Spatie\Permission\Traits\HasRoles
in User modelRefer: codeanddeploy.com/blog/laravel/lar...
My code is similar to the one in the reference, here It's my user model.
`<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
}`