DEV Community

Alejandro Reyes
Alejandro Reyes

Posted on

HELP, Problem with Laravel-Permission

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);

}
Enter fullscreen mode Exit fullscreen mode

}

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
kiennguye1911 profile image
Nguyễn Đồng Kiên

You may not use use Spatie\Permission\Traits\HasRoles in User model

Refer: codeanddeploy.com/blog/laravel/lar...

Collapse
 
alereyes profile image
Alejandro Reyes

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;

/**
 * The attributes that are mass assignable.
 *
 * @var array<int, string>
 */
protected $fillable = [
    'name',
    'email',
    'password',
    'estado'
];

/**
 * The attributes that should be hidden for serialization.
 *
 * @var array<int, string>
 */
protected $hidden = [
    'password',
    'remember_token',
];

/**
 * The attributes that should be cast.
 *
 * @var array<string, string>
 */
protected $casts = [
    'email_verified_at' => 'datetime',
    'password' => 'hashed',
];

public function titulares()
{
    return $this->hasMany(Titular::class);
}

public function beneficiarios()
{
    return $this->hasMany(Beneficiario::class);
}
Enter fullscreen mode Exit fullscreen mode

}`

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay