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
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.