NaturalDevCR
NaturalDevCR

Reputation: 852

updateOrCreate Laravel Eloquent inside a foreach issue?

so i'm trying to use the updateOrCreate Eloquent Method inside a foreach statement, but it's creating duplicated new models instead of updating the existing ones.

Here is a piece of my controller:

$user = Auth::user()->id;

    $providers = Providers::where('user_id', $user)->where('provider_status', 0)->get(['provider_id']);

    //dd($providers);

    //Months

    $now = Carbon::now()->setTimezone('America/Costa_Rica');;

    $currentYear = $now->copy()->year;

    foreach($providers as $provider) {

        //January

        //Month
        $janFrom = $now->copy()->month(1)->startOfMonth();
        $janTo = $now->copy()->month(1)->endOfMonth();

        $janPriceMonthTotal = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFrom, $janTo])->sum('price');

        //Fortnights
        //First
        $janFromFortnightFirst = $janFrom->copy();
        $janToFortnightFirst = $janFromFortnightFirst->copy()->addDays(14);

        $janPriceFortnightFirst = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFromFortnightFirst, $janToFortnightFirst])->sum('price');
        $janExpensesFortnightFirst = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFromFortnightFirst, $janToFortnightFirst])->sum('travel_expenses');

        //Last
        $janFromFortnightLast = $janFromFortnightFirst->copy()->addDays(15);
        $janToFortnightLast = $janTo->copy();

        $janPriceFortnightLast = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFromFortnightLast, $janToFortnightLast])->sum('price');
        $janExpensesFortnightLast = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFromFortnightLast, $janToFortnightLast])->sum('travel_expenses');

        $janEventCount = Planillas::where('user_id', $user)->where('status', 0)->where('deleted', 0)->where('provider', $provider->provider_id)->whereBetween('date', [$janFrom, $janTo])->count();

        //dd($janEventCount);
        //Update if exists or create if doesn't
        $janMonth = ProviderReport::updateOrCreate([
            'user_id' => $user,
            'status' => 1,
            'month' => 'jan',
            'year' => $currentYear,
            'provider_id' => $provider->provider_id,
        ],
            [
                'monthly_total' => $janPriceMonthTotal,
                'first_fortnight' => $janPriceFortnightFirst,
                'second_fortnight' => $janPriceFortnightLast,
                'expenses_first' => $janExpensesFortnightFirst,
                'expenses_last' => $janExpensesFortnightLast,
                'event_count' => $janEventCount,
            ]);
    }

My model here:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProviderReport extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'month',
        'year',
        'first_fortnight',
        'second_fortnight',
        'monthly_total',
        'expenses_first',
        'expenses_last',
        'provider_id',
        'event_count',
    ];
}

The issue is that the first time the code runs, and no data is in my table, then it's created pretty well, but when i run the code again (let's say i changed something like the event_count, then creates duplicates instead of updating my rows.

Thanks in advance for your time.

Upvotes: 2

Views: 1599

Answers (1)

NaturalDevCR
NaturalDevCR

Reputation: 852

Ok, so i found the mistake, and was on my model... sorry i asked, but anyway, for anyone with this issue.

My model was:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProviderReport extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'month',
        'year',
        'first_fortnight',
        'second_fortnight',
        'monthly_total',
        'expenses_first',
        'expenses_last',
        'provider_id',
        'event_count',
    ];
}

Fixed:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class ProviderReport extends Model
    {
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'user_id',
            'month',
            'year',
            'first_fortnight',
            'second_fortnight',
            'monthly_total',
            'expenses_first',
            'expenses_last',
            'provider_id',
            'event_count',
            'status', // i forgot to add this
        ];
    }

but i forgot to add 'status' to my $fillable, also, status had the default value of 0 in my table, so when updateOrCreate checked for existence of my model, was never found, because the newly created rows had the 'status' set to zero by default, and that colum wasn't listed in $fillable in model.

Upvotes: 1

Related Questions