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

shahr's avatar
Level 10

firstOrCreate or firstOrNew not working

I have a row in educationals table

table

And my form is like this demo

form

When I click Add other academic record, it add new row, and when I'm filling new data And in the last step, when I click on the submit, nothing happens in the database.

The first method:

foreach ($request->field as $key => $value) {
    $educational = Educational::firstOrNew(['user_id' => auth()->id()]);
    $educational->user_id = auth()->id();
    $educational->grade_id = $request->grade_id[$key];
    $educational->field = $request->field[$key];
    $educational->institution_id = $request->institution_id[$key];
    $educational->branch = $request->branch[$key];
    $educational->institution_education = $request->institution_education[$key];
    $educational->gpa = $request->gpa[$key];
    $educational->nation_id = $request->nation_id[$key];
    $educational->province_id = $request->province_id[$key];
    $educational->town_id = $request->town_id[$key];
    $educational->province_name = $request->province_name[$key];
    $educational->town_name = $request->town_name[$key];
    $educational->entrance = $request->entrance[$key];
    $educational->graduate = $request->graduate[$key];
    $educational->currently_studying = $request->has("currently_studying.$key");
    $educational->save();
}

The second method:

foreach ($request->field as $key => $value) {
    try {
        $educational = new Educational;
        $educational->user_id = auth()->id();
        $educational->grade_id = $request->grade_id[$key];
        $educational->field = $request->field[$key];
        $educational->institution_id = $request->institution_id[$key];
        $educational->branch = $request->branch[$key];
        $educational->institution_education = $request->institution_education[$key];
        $educational->gpa = $request->gpa[$key];
        $educational->nation_id = $request->nation_id[$key];
        $educational->province_id = $request->province_id[$key];
        $educational->town_id = $request->town_id[$key];
        $educational->province_name = $request->province_name[$key];
        $educational->town_name = $request->town_name[$key];
        $educational->entrance = $request->entrance[$key];
        $educational->graduate = $request->graduate[$key];
        $educational->currently_studying = $request->has("currently_studying.$key");
        $educational->save();
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

The third method

foreach ($request->field as $key => $value) {
    Educational::firstOrCreate([
        'user_id' => auth()->id(),
        'grade_id' => $request->grade_id[$key],
        'field' => $request->field[$key],
        'institution_id' => $request->institution_id[$key],
        'branch' => $request->branch[$key],
        'institution_education' => $request->institution_education[$key],
        'gpa' => $request->gpa[$key],
        'nation_id' => $request->nation_id[$key],
        'province_id' => $request->province_id[$key],
        'town_id' => $request->town_id[$key],
        'province_name' => $request->province_name[$key],
        'town_name' => $request->town_name[$key],
        'entrance' => $request->entrance[$key],
        'graduate' => $request->graduate[$key],
        'currently_studying' => $request->has("currently_studying.$key"),
    ]);
}

The fourth method

foreach ($request->field as $key => $value) {
    try {
    $educational = Educational::firstOrCreate(['user_id' => auth()->id()]);
        $educational->user_id = auth()->id();
        $educational->grade_id = $request->grade_id[$key];
        $educational->field = $request->field[$key];
        $educational->institution_id = $request->institution_id[$key];
        $educational->branch = $request->branch[$key];
        $educational->institution_education = $request->institution_education[$key];
        $educational->gpa = $request->gpa[$key];
        $educational->nation_id = $request->nation_id[$key];
        $educational->province_id = $request->province_id[$key];
        $educational->town_id = $request->town_id[$key];
        $educational->province_name = $request->province_name[$key];
        $educational->town_name = $request->town_name[$key];
        $educational->entrance = $request->entrance[$key];
        $educational->graduate = $request->graduate[$key];
        $educational->currently_studying = $request->has("currently_studying.$key");
        $educational->save();
    } catch (Exception $e) {
        dd($e->getMessage());
    }
}

The fifth method

public function update(Request $request) {
    $user = auth()->user();
    $user->image = $path;
    $user->first_name = $request->first_name;
    $user->last_name = $request->last_name;
    $user->job_title = $request->job_title;
    $user->gender = $request->gender;
    $user->marital = $request->marital;
    $user->soldier_id = $request->soldier_id;
    $user->birth_date_day = $request->birth_date_day;
    $user->month_id = $request->month_id;
    $user->birth_date_year = $request->birth_date_year;
    $user->email = $request->email;
    $user->mobile = $request->mobile;
    $user->telephone = $request->telephone;
    $user->website = $request->website;
    $user->save();
    foreach ($request->field as $key => $value) {
        if ($user->where('user_id', auth()->id())) {
            $educational = $user->findOrFail('user_id');
        } else {
            $educational = new Educational;
        }
        $educational->user_id = auth()->id();
        $educational->grade_id = $request->grade_id[$key];
        $educational->field = $request->field[$key];
        $educational->institution_id = $request->institution_id[$key];
        $educational->branch = $request->branch[$key];
        $educational->institution_education = $request->institution_education[$key];
        $educational->gpa = $request->gpa[$key];
        $educational->land_id = $request->land_id[$key];
        $educational->province_id = $request->province_id[$key];
        $educational->town_id = $request->town_id[$key];
        $educational->province_name = $request->province_name[$key];
        $educational->town_name = $request->town_name[$key];
        $educational->entrance = $request->entrance[$key];
        $educational->graduate = $request->graduate[$key];
        $educational->currently_studying = $request->has("currently_studying.$key");
        $educational->save();
    }
} 

educationals table

public function up()
{
    Schema::create('educationals', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->bigInteger('grade_id')->unsigned()->nullable();
        $table->foreign('grade_id')->references('id')->on('grades')->onDelete('cascade');
        $table->string('field')->nullable();
        $table->bigInteger('institution_id')->unsigned()->nullable();
        $table->foreign('institution_id')->references('id')->on('institutions')->onDelete('cascade');
        $table->string('branch')->nullable();
        $table->string('institution_education')->nullable();
        $table->string('gpa')->nullable();
        $table->bigInteger('country_id')->unsigned()->nullable();
        $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
        $table->bigInteger('state_id')->unsigned()->nullable();
        $table->foreign('state_id')->references('id')->on('states')->onDelete('cascade');
        $table->bigInteger('city_id')->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        $table->string('state_name')->nullable();
        $table->string('city_name')->nullable();
        $table->string('entrance')->nullable();
        $table->string('graduate')->nullable();
        $table->boolean('currently_studying')->nullable();
        $table->timestamps();
    });
}

My blade

<div class="container-fluid">
    <b>سوابق تحصیلی</b>
    <div class="mb-2 bg-white p-3 mb-5">
        <div class="row p-3" id="showStudy">

        </div>
        <div class="w-100 text-center">
            <p>سوابق تحصیلی دیگری را اضافه کنید.</p>
            <a id="addStudy" class="bg-primary text-white pt-2 pb-2 pl-3 pr-3 rounded-circle cursor-pointer">
                <i class="fas fa-plus"></i>
            </a>
        </div>
    </div>
</div>

<script>    
    $(document).ready(function() {
        let countStudy = 1;
        $('#addStudy').click(function () {
            countStudy++;
            dynamicStudy(countStudy);
        });
        //dynamicStudy(countStudy);
        function dynamicStudy(number) {
            let html = '' +
                '<div class="col-md-12 position-relative">\n' +
                '<i class="fas fa-times text-danger position-absolute"></i>' +
                '<div class="row">\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="grade_id">مقطع</label>\n' +
                '<select id="grade_id" name="grade_id[]" class="form-control">\n' +
                '@foreach($grades as $grade)\n' +
                '<option value="{{ $grade->id }}">\n' +
                '{{ $grade->name }}\n' +
                '</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="field">رشته تحصیلی</label>\n' +
                '<input id="field" name="field[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="branch">گرایش/تخصص</label>\n' +
                '<input id="branch" name="branch[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="institution_id">نوع موسسه</label>\n' +
                '<select id="institution_id" name="institution_id[]" class="form-control">\n' +
                '@foreach($institutions as $institution)\n' +
                '<option value="{{ $institution->id }}">{{ $institution->name }}</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="institution_education">عنوان موسسه آموزشی</label>\n' +
                '<input id="institution_education" name="institution_education[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="gpa">معدل</label>\n' +
                '<input id="gpa" name="gpa[]" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="nation_id">کشور</label>\n' +
                '<select id="nation_id" name="nation_id[]" class="form-control">\n' +
                '<option></option>\n' +
                '@foreach($countries as $country)\n' +
                '<option value="{{ $country->id }}">{{ $country->name }}</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="province_id">استان</label>\n' +
                '<select id="province_id" name="province_id[]" class="form-control">\n' +
                '</select>\n' +
                '<input name="province_name[]" id="province_id" class="form-control d-none">\n'+
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="town_id">شهر</label>\n' +
                '<select id="town_id" name="town_id[]" class="form-control">\n' +
                '</select>\n' +
                '<input name="town_name[]" id="town_id" class="form-control d-none">\n'+
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="entrance">ورود</label>\n' +
                '<input name="entrance[]" id="entrance" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="graduate">فراغت از تحصیل</label>\n' +
                '<input name="graduate[]" id="graduate" class="form-control">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<div class="custom-control custom-checkbox my-4 mr-sm-2">\n' +
                '<input type="checkbox" class="custom-control-input" id="currently_studying" name="currently_studying[]">\n' +
                '<label class="custom-control-label" for="currently_studying">در حال تحصیل</label>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>';
            $('#showStudy').append(html);
        }

        showDynamicStudy();
        function showDynamicStudy(){
            let html = '' +
                '@foreach(auth()->user()->educationals as $educational)\n'+
                '<div class="col-md-12 position-relative">\n' +
                '<i class="fas fa-times text-danger position-absolute"></i>' +
                '<div class="row">\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="grade_id">مقطع</label>\n' +
                '<select id="grade_id" name="grade_id[]" class="form-control">\n' +
                '@foreach($grades as $grade)\n' +
                '<option value="{{ $grade->id }}" {{ $educational->grade_id == $grade->id ? 'selected' : '' }}>\n' +
                '{{ $grade->name }}\n' +
                '</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="field">رشته تحصیلی</label>\n' +
                '<input id="field" name="field[]" class="form-control" value="{{ $educational->field }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="branch">گرایش/تخصص</label>\n' +
                '<input id="branch" name="branch[]" class="form-control" value="{{ $educational->branch }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="institution_id">نوع موسسه</label>\n' +
                '<select id="institution_id" name="institution_id[]" class="form-control">\n' +
                '@foreach($institutions as $institution)\n' +
                '<option value="{{ $institution->id }}" {{ $educational->institution_id == $institution->id ? 'selected' : '' }}>{{ $institution->name }}</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="institution_education">عنوان موسسه آموزشی</label>\n' +
                '<input id="institution_education" name="institution_education[]" class="form-control" value="{{ $educational->institution_education }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="gpa">معدل</label>\n' +
                '<input id="gpa" name="gpa[]" class="form-control" value="{{ $educational->gpa }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="nation_id">کشور</label>\n' +
                '<select id="nation_id" name="nation_id[]" class="form-control">\n' +
                '<option></option>\n' +
                '@foreach($countries as $country)\n' +
                '<option value="{{ $country->id }}" {{ $educational->nation_id == $country->id ? 'selected' : '' }}>\n' +
                '{{ $country->name }}\n'+
                '</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="province_id">استان</label>\n' +
                '<select id="province_id" name="province_id[]" class="form-control">\n' +
                '@foreach($states as $state)\n' +
                '<option value="{{ $state->id }}" {{ $educational->province_id == $state->id ? 'selected' : '' }}>\n' +
                '{{ $state->name }}\n' +
                '</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '<input name="province_name[]" id="province_id" class="form-control d-none" value="{{ $educational->province_name }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="town_id">شهر</label>\n' +
                '<select id="town_id" name="town_id[]" class="form-control">\n' +
                '@foreach($cities as $city)\n' +
                '<option value="{{ $city->id }}" {{ $educational->town_id == $city->id ? 'selected' : '' }}>\n' +
                '{{ $city->name }}\n' +
                '</option>\n' +
                '@endforeach\n' +
                '</select>\n' +
                '<input name="town_name[]" id="town_id" class="form-control d-none" value="{{ $educational->town_name }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="entrance">ورود</label>\n' +
                '<input name="entrance[]" id="entrance" class="form-control" value="{{ $educational->entrance }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<label for="graduate">فراغت از تحصیل</label>\n' +
                '<input name="graduate[]" id="graduate" class="form-control" value="{{ $educational->graduate }}">\n' +
                '</div>\n' +
                '</div>\n' +
                '<div class="col-md-2">\n' +
                '<div class="form-group">\n' +
                '<div class="custom-control custom-checkbox my-4 mr-sm-2">\n' +
                '<input type="checkbox" class="custom-control-input" id="currently_studying" name="currently_studying[]" {{ $educational->currently_studying == 1 ? 'checked' : '' }}>\n' +
                '<label class="custom-control-label" for="currently_studying">در حال تحصیل</label>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>\n' +
                '@endforeach';
            $('#showStudy').append(html);
        }
    });
</script>

I used all five methods but none of them worked. And not stored in the database.

0 likes
58 replies
Sinnbeck's avatar

Do you understand how these methods work or are you just trying random things? I suggest trying to understand how at least one of them works, to be able to actually use it

shahr's avatar
Level 10

@sinnbeck

I used all five methods but none of them worked. And not stored in the database.

Snapey's avatar

What a mess

If you want to use firstOrNew you have to use the id of the record you want to find, not the id of the user

Sinnbeck's avatar

Oh and if it does not trigger, that means $request->field is empty :)

Sinnbeck's avatar

@jlrdw Yeah is states the same :)

The firstOrNew method is really useful for finding the first Model that matches some constraints or making a new one if there isn’t one that matches those constraints.

jlrdw's avatar

@sinnbeck exactly.

Edit: The examples are so clear on how to use.

Edit two: To add to @sinnbeck answer, not only dd, but use the network tab also (as needed).

@snapey is the one who got me to use it, and what a big help it is.

Snapey's avatar

@snapey Actually I do believe it works with an arbitrary column..

@sinnbeck yes it does, but not when that it is the fk of a hasMany relationship. All that would happen now is that the existing record is found, and never that a new record is created.

Sinnbeck's avatar

@snapey oh yes good point. :) didn't catch that it has a hasMany. Figured one to one

Sinnbeck's avatar

So that is the record you wish to update? Or did you expect a new one?

shahr's avatar
Level 10

@sinnbeck

Yes, I was expecting something new. And the fact that I clicked on + I entered dd I did it also showed the one computer.

shahr's avatar
Level 10

@sinnbeck -

I was expecting something new, I used all five methods but none of them worked. And not stored in the database.

shahr's avatar
Level 10

The migration for table

public function up()
{
    Schema::create('educationals', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned()->nullable();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->bigInteger('grade_id')->unsigned()->nullable();
        $table->foreign('grade_id')->references('id')->on('grades')->onDelete('cascade');
        $table->string('field')->nullable();
        $table->bigInteger('institution_id')->unsigned()->nullable();
        $table->foreign('institution_id')->references('id')->on('institutions')->onDelete('cascade');
        $table->string('branch')->nullable();
        $table->string('institution_education')->nullable();
        $table->string('gpa')->nullable();
        $table->bigInteger('country_id')->unsigned()->nullable();
        $table->foreign('country_id')->references('id')->on('countries')->onDelete('cascade');
        $table->bigInteger('state_id')->unsigned()->nullable();
        $table->foreign('state_id')->references('id')->on('states')->onDelete('cascade');
        $table->bigInteger('city_id')->unsigned()->nullable();
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        $table->string('state_name')->nullable();
        $table->string('city_name')->nullable();
        $table->string('entrance')->nullable();
        $table->string('graduate')->nullable();
        $table->boolean('currently_studying')->nullable();
        $table->timestamps();
    });
}
automica's avatar

@oxbir I feel like we've had this conversation already today.

please follow along all steps!

1 - your input is study['+countStudy+'][grade_id] so first will be study[0][grade_id]

2 - your request is $request->study.

if you

dd($request->study)

you will see an array of objects

3 - if you want to see the first item for grade_id you will see it as:

$request->study[0]->grade_id

BUT!!!

4 - in your save method you are trying to save:

$request->input['grade_id']

so this will not work because it is different to (3)

AND!

5 - you want to create new Educational model if it doesn't already exist for your user.

the docs for first or create gives 2 examples

// Retrieve flight by name, or create it if it doesn't exist...
$flight = App\Models\Flight::firstOrCreate(['name' => 'Flight 10']);

// Retrieve flight by name, or create it with the name, delayed, and arrival_time attributes...
$flight = App\Models\Flight::firstOrCreate(
    ['name' => 'Flight 10'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

yours is like the second answer where you find an existing Educational record for that user or create if this doesn't already exist.

THIS WILL ONLY PRODUCE 1 RECORD as for second row of your form you just retrieve the first one again.

so you need to use first approach, with one group of arguments.

6 - Please read above, acknowledge you understand, and then tell me what you think you should do next.

If I give you the answer, it is like I am giving you a fish.

You don't need a fish.

You need to learn to fish.

1 like
Snapey's avatar

why do you have the field names inside square braces? This is not what was advised.

shahr's avatar
Level 10

Then tell me what you think you should do next.

I want to save in database.

shahr's avatar
Level 10

Yes , but my problem did not so;ve yet.

Next

Please or to participate in this conversation.