Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincentsanity's avatar

Laravel Check record if exist throw exception

I have a original code in my update statement like this

 $schedule = Schedule::findOrFail($id);
        $schedule->subject_code_id = $request->subject;
        $schedule->teacher_id = $request->teacher;
        $schedule->room_id = $request->room;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->school_year = $request->schoolyr;
        $schedule->semester = $request->sem;
        $schedule->term = $request->term;
        $schedule->day = $request->days;
        $schedule->update($request->all());

I modified it to

  $schedule = Schedule::findOrFail($id);

        
        $schedule->subject_code_id = $request->subject;
        $schedule->teacher_id = $request->teacher;
        $schedule->room_id = $request->room;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->school_year = $request->schoolyr;
        $schedule->semester = $request->sem;
        $schedule->term = $request->term;
        $schedule->day = $request->days;

        $update = $request->all();
        // dd($update);
        // $schedule->update($request->all());

        if(is_null($update)){
            dd('Not Exist');
        }else{
            dd('Exist');
        }

But i keep getting Exist.. anyone know whats the problem? Thanks

0 likes
50 replies
Nakov's avatar

@vincentsanity as Scooby said, don't check for null check the array size instead:

if(count($update) === 0) {
   dd('Not Exist');
} else {
   dd('Exist');
}
1 like
kevinbui's avatar

Instead of is_null(), you can use empty().

Nakov's avatar

@vincentsanity what is the result when you do:

dd($update);

Your array is probably not empty then :)

vincentsanity's avatar

No. I just want to throw an exception if the user updates the data that has been in the database. @scooby

tykus's avatar

What @scooby said, but what are you actually checking anyway? If the Schedule doesn't exist you will already have had a ModelNotFoundException, the Request will always have something, even an empty array

Aside, you are going to have the problem that the keys in the request do not map directly to the attributes in the Schedule model - you would need to map over the request to normalize the attribute names.

Also, be wary of $request->all(), better (IMHO) to use $request->only(['subject', 'teacher', ...]) or, even better to validate the incoming request data, and use that as the array of updated attributes:

$validatedData = $request->validate([
    'subject' => ['required', Rule::exists('subject_codes')]
    // ... etc
]);

$schedule->update($validatedData);
vincentsanity's avatar

I just want to check when the user clicks update and the request data is already existed in the database, It will throw error. @tykus

Scooby's avatar

Maybe something like this..

$schedule = Schedule::find($id);

if ($schedule->exists()) {
    // dd('Exist');
} else {
    // dd('Not Exist');
}
vincentsanity's avatar

I tried @tykus.. seems not working?

$schedule = Schedule::findOrFail($id);
        $schedule->subject_code_id = $request->subject;
        $schedule->teacher_id = $request->teacher;
        $schedule->room_id = $request->room;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->school_year = $request->schoolyr;
        $schedule->semester = $request->sem;
        $schedule->term = $request->term;
        $schedule->day = $request->days;

        // $update = $request->all();

        // $schedule_exist = $request->all()->exists();
        // dd($update);
        // $schedule->update($request->all());

        $validatedData = $request->validate([
            'subject' => ['required', Rule::exists('subject_code_id')],
            'teacher' => ['required', Rule::exists('teacher_id')],
            'room' => ['required', Rule::exists('room_id')],
            'start_time' => ['required', Rule::exists('start_time')],
            'end_time' => ['required', Rule::exists('end_time')],
            'schoolyr' => ['required', Rule::exists('school_year')],
            'sem' => ['required', Rule::exists('semester')],
            'term' => ['required', Rule::exists('term')],
            'days' => ['required', Rule::exists('days')],
        ]);
        dd($validatedData);
        $schedule->update($validatedData);
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'capstoneproject.start_time' doesn't exist (SQL: select count(*) as aggregate from `start_time` where `start_time` = 10:30 PM)"
exception: "Illuminate\Database\QueryException"
Snapey's avatar

What ARE you doing?

Store all the values in the database and THEN validate it? What exactly is this function trying to do (in plain words).

By the way, the reason for the error is that you are checking exists, the first parameter of which is the table name you want to check in.

vincentsanity's avatar

no @snapey . Check all values if exist in the database then if it exists throw an exception if not then update/insert.

tykus's avatar

Just to be clear you are not updating or inserting, you are checking for the existence of the Model instance using findOrFail. If there is not model, your will have a ModelNotFoundException, thereafter, you can fill that model instance from the request and check for changed attributes using getDirty().

If you intention is to create or update, then the approach will be different; you will use the createOrUpdate method. It takes two arrays, (i) the attributes used to find any existing records and (ii) the additional attributes (that in combination with (i) will update existing or create a new record.

Scooby's avatar

Well if you're throwing an exception if the record exists then you'd only be creating so has to be this..

$schedule = Schedule::find($id);

if ($schedule->exists()) {
    throw new Exception('Record exists');
} else {
    $schedule->create($request->validate([
        'subject' => 'required',
        ...
    ]);
}
1 like
experimentor's avatar

@vincentsanity Please check what @scooby said a few minutes ago. That is correct.

But, you first need to get $id. Hope you are sending in request.

is $id == $request->id I mean are you sending the schedule's ID in the request?

If yes, do what @scooby said

$id = $request->id;
$schedule = Schedule::find($id);

if ($schedule->exists()) {
    throw new Exception('Record exists');
} else {
    $schedule->create($request->validate([
        'subject' => 'required',
        ...
    ]);
}
vincentsanity's avatar

@capper33 . when I update, I get the id first of the updated data. then if the updated data has a duplicate values of all the request except for the id. it will not update instead i want to write dd('existed');and if not then update the all of the request except for the id.

tykus's avatar

@vincentsanity I mean that what you are saying doesn't make a lot of sense. There is a disconnect between what you are saying and what your code is expressing. You need to be clear what you are trying to achieve.

Snapey's avatar

which fields should not be the same?

1 like
vincentsanity's avatar

@capper33 I keep getting exist even if i update the data in my form

 $id = $request->id;
        $schedule = Schedule::find($id);

        $schedule->subject_code_id = $request->subject;
        $schedule->teacher_id = $request->teacher;
        $schedule->room_id = $request->room;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->school_year = $request->schoolyr;
        $schedule->semester = $request->sem;
        $schedule->term = $request->term;
        $schedule->day = $request->days;

        if ($schedule->exists()) {
            dd('exist');
        } else {
            $schedule->update($request->validate([
                'subject' => ['required', Rule::exists('subject_code_id')],
                'teacher' => ['required', Rule::exists('teacher_id')],
                'room' => ['required', Rule::exists('room_id')],
                'start_time' => ['required', Rule::exists('start_time')],
                'end_time' => ['required', Rule::exists('end_time')],
                'schoolyr' => ['required', Rule::exists('school_year')],
                'sem' => ['required', Rule::exists('semester')],
                'term' => ['required', Rule::exists('term')],
                'days' => ['required', Rule::exists('days')],  
            ]));
        }

What should be the problem?

vincentsanity's avatar

all the fields except for @id @snapey . Because it is a schedule. No schedule should be in the same room_id and time and also days

experimentor's avatar

@vincentsanity

I'm assuming a Schedule is defined uniquely by Teacher , subject, room and start time.

So, you need to check if there exists a Schedule in our database with the same combination of values.

So you do this

$existing_schedule = Schedule::where('teacher', $request->teacher)
->where('subject_code_id', $request->subject)
->where('room_id', $request->room)
->where('start_time', $request->start_time)
->first();

if ($existing_schedule->exists()) {
    dd('Exist');
} else {
    $schedule->subject_code_id = $request->subject;
        $schedule->teacher_id = $request->teacher;
        $schedule->room_id = $request->room;
        $schedule->start_time = $request->start_time;
        $schedule->end_time = $request->end_time;
        $schedule->school_year = $request->schoolyr;
        $schedule->semester = $request->sem;
        $schedule->term = $request->term;
        $schedule->day = $request->days;
    $schedule->save();
}

Hope this is what you are looking for.

1 like
tykus's avatar

exists checks for the presence of the Model in the database (you have found the Model by its id).

It does not check if the new attributes that you have assigned already exist on a different record in the database.

Also, what you're doing is redundant - you assign to the Model properties, then separately run an update. Your Rule::exists expression will not work because you have not used the correct syntax either,.

1 like
Mohammed-H's avatar

Maybe a simple query with where and orWhere is what you need?

vincentsanity's avatar

I tried @capper33 but i keep getting exist even if i change all the values in the form. And also, no need to get the id for the schedule when updating it?

   $existing_schedule = Schedule::where('teacher_id', $request->teacher)
                ->where('id',$request->scid)
                ->where('subject_code_id', $request->subject)
                ->where('room_id', $request->room)
                ->where('start_time', $request->start_time)
                ->where('end_time', $request->end_time)
                ->where('day',$request->day)
                ->first();
                if ($schedule->exists()) {
                    dd('Exist');
                } else {
                    $schedule->subject_code_id = $request->subject;
                        $schedule->teacher_id = $request->teacher;
                        $schedule->room_id = $request->room;
                        $schedule->start_time = $request->start_time;
                        $schedule->end_time = $request->end_time;
                        $schedule->school_year = $request->schoolyr;
                        $schedule->semester = $request->sem;
                        $schedule->term = $request->term;
                        $schedule->day = $request->days;
                    $schedule->save();
          
Mohammed-H's avatar
  $existing_schedule = Schedule::where('teacher_id', $request->teacher)
                ->where('subject_code_id', $request->subject)
                ->where('room_id', $request->room)
                ->where('start_time', $request->start_time)
                ->where('end_time', $request->end_time)
                ->where('day',$request->day)
                ->first();
                if ($existing_schedule) {
                    dd('Exist');
                } else {
                    $schedule->subject_code_id = $request->subject;
                        $schedule->teacher_id = $request->teacher;
                        $schedule->room_id = $request->room;
                        $schedule->start_time = $request->start_time;
                        $schedule->end_time = $request->end_time;
                        $schedule->school_year = $request->schoolyr;
                        $schedule->semester = $request->sem;
                        $schedule->term = $request->term;
                        $schedule->day = $request->days;
                    $schedule->save();
Next

Please or to participate in this conversation.