Sermed mayi
Sermed mayi

Reputation: 757

How prevent save same record many times

I have controller recieve 12 request from flutter app, the request is like this:

data.map((e) async {
      Map list = {
        'username': username,
        'club': e.club,
        'price': e.price,
        'surename': e.surname,
        'id': e.id,
        'league': e.leagueName,
      };
      try {
        var newurl = Uri.parse(url + 'create_team');
        var response =
            await http.post(newurl, body: jsonEncode(list), headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        });
        var result = jsonDecode(response.body);
        print(result);
      } catch (e) {
        print('error : $e');
      }
    }).toList();

my controller method :

public function create_team(Request  $request)
    {
       
        $user=User::where('username',$request->username)->first();
        
        $week = Week::where('status','active')->first();
        $week_id = $week->id;
        
        $club = Club::where('club',$request->club)->first();

        $created_team=Team::where('user_id',$user->id)->get();
        if($created_team->count()==0){
            $team = Team::create([
            'team_name'=> '',
            'season_id'=> 1,
            'week_id'=> $week_id,
            'user_id'=>$user->id,
        ]);
        $team_id = Team::where('user_id',$user->id)->where('week_id',$week_id)->first();
        $insert=UserTeam::create([
            'team_id'=> $team_id->id,
            'club_id'=> $club->id,  
        ]);
        }else{
            $team_id = Team::where('user_id',$user->id)->where('week_id',$week_id)->first();
            $insert=UserTeam::create([
                'team_id'=> $team_id->id,
                'club_id'=> $club->id,  
            ]);
        }
        return response()->json(['message' => 'Succed']);
    }

in controller I made it to check if team is saved before to saved it once but it dosn't work all time ,many times it is save more than one . Now how can i stop this to save more than one time?

Upvotes: 0

Views: 373

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

You can simply use firstOrCreate() method on your model.

Team::firstOrcreate([
    'team_name'=> '',
    'season_id'=> 1,
    'week_id'=> $week_id,
    'user_id'=>$user->id,
]);

It won't create new team if it already exists. For more info refer to here

Upvotes: 1

Related Questions