skip to Main Content

i am in learning rest API laravel, in this case
I want to limit the user to only be able to create 1 team, but after just testing with Postman, when the user has created more than 1 team, the default display is Laravel’s status code 200
what should appear is the error response that I have set

error view

here is my code:

Controller

public function createTeam(CreateTeamRequest $request)
{

    try {
        $user = auth()->user();
        $team = Team::where('user_id', $user->id)->first();
        $access_token = $user->remember_token;
        if ($team->user_id->exists()) {
            return $this->messageError('Kamu hanya dapat membuat 1 team!', 422);
        } else {
            $team = Team::create(array_merge(
                $request->all(),
                [
                    'user_id' => $user->id,
                ]
            ));
            return $this->messageSuccess(['data' => $team, 'header' => ['access_token' => $access_token]], "Berhasil membuat tim", 200);
        }

    } catch (Exception $e) {
        return $this->messageError('Terjadi Kesalahan' . $e->getMessage(), 422);
    }

}

Model

class Team extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'user_id'
    ];

    public function members()
    {
        return $this->belongsToMany(User::class);
    }

}

Migration

public function up(): void
{
    Schema::create('teams', function (Blueprint $table) {
        $table->id();
        $table->string('name')->unique();
        $table->timestamps();

        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

    Schema::create('team_user', function (Blueprint $table) {
        $table->unsignedBigInteger('team_id');
        $table->unsignedBigInteger('user_id');

        $table->foreign('team_id')->references('id')->on('teams')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->primary(['team_id', 'user_id']);
    });

}

I want when a user has created more than 1 team, an error message will appear

2

Answers


  1. Based on the provided code, I can see that you’re trying to restrict users from creating more than one team. If a user already has a team, you want to return an error message.

    However, there is an issue with the code logic in your createTeam method. Instead of checking if $team->user_id->exists() (which is incorrect), you should check if $team exists. Here’s the corrected code:

    public function createTeam(CreateTeamRequest $request)
    {
        try {
            $user = auth()->user();
            $team = Team::where('user_id', $user->id)->first();
            $access_token = $user->remember_token;
    
            if ($team) {
                return $this->messageError('Kamu hanya dapat membuat 1 team!', 422);
            } else {
                $team = Team::create(array_merge(
                    $request->all(),
                    [
                        'user_id' => $user->id,
                    ]
                ));
                return $this->messageSuccess(['data' => $team, 'header' => ['access_token' => $access_token]], "Berhasil membuat tim", 200);
            }
        } catch (Exception $e) {
            return $this->messageError('Terjadi Kesalahan' . $e->getMessage(), 422);
        }
    }
    

    In the updated code, we check if $team exists using if ($team) instead of $team->user_id->exists(). If $team is not null (i.e., a team exists for the user), we return an error message using the messageError method with a status code of 422.

    Please note that the code provided assumes that the messageError and messageSuccess methods are defined in the controller or a related class. Make sure you have implemented these methods properly for handling the error and success responses.

    Login or Signup to reply.
  2. public function createTeam(CreateTeamRequest $request)
    {
        try {
            $user = auth()->user();
            $access_token = $user->remember_token;
    
            if ($user->team()->exists()) {
                return $this->messageError('Kamu hanya dapat membuat 1 team!', 422);
            } else {
                $team = Team::query()->create(array_merge(
                    $request->validated(),
                    [
                        'user_id' => $user->id,
                    ]
                ));
                return $this->messageSuccess(['data' => $team, 'header' => ['access_token' => $access_token]], "Berhasil membuat tim", 200);
            }
        } catch (Exception $e) {
            return $this->messageError('Terjadi Kesalahan' . $e->getMessage(), 500);
        }
    }
    

    Here I use team() relationship defined in AppModelsUser::class to check if this user already has a team.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search