1

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 one team, an error message will appear.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
zal
  • 11
  • 1
  • 1
    Just dump your `$team` variable in your code, using Xdebug for example and debug your code, I don't understand `$team->user_id->exists()`, take a look here: https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists – Vincent Decaux Jun 21 '23 at 12:32
  • 2
    And what's your question about this? What have you tried to resolve your problem? Where are you stuck? Are you sure this problem is in any way related to Postman? – Nico Haase Jun 21 '23 at 12:33
  • @VincentDecaux ,what $team->user_id->exists() means I want to check if the team was created again by the same user_id ? because I want to limit the user to only be able to create 1 team – zal Jun 21 '23 at 12:43
  • 1. please change the `accept` header to `application/json` 2. `dd()` each block to see if you actually are in the intended block 3. `HttpResponseException` is a better approach to handle error responses while you're developing a RESTful API – Arian Sakhaei Jun 21 '23 at 14:15
  • if I were you, I'd create a custom validation rule and used it in `CreateTeamRequest ` class – Arian Sakhaei Jun 21 '23 at 14:21

1 Answers1

0
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 App\Models\User::class to check if this user already has a team.

kris gjika
  • 531
  • 2
  • 8
  • thank you for the answer, the team() function is not recognized even though I have called the class use App\Models\User , but I tried with $user->team but the result is that when a user creates a team of more than 1 a status code 200 will appear – zal Jun 21 '23 at 13:03
  • @zal you need to define the team relation in your `App\Models\User::class`, similar to how you have done for `members()` – kris gjika Jun 21 '23 at 15:46
  • @zal if the `team()` relation is not defined, `$user->team` will always be `null` and your check will fail. – kris gjika Jun 21 '23 at 15:48