2

I want to create data but if the data already in database, it will update. but if the data not already in database, it will create new data.

this my controller

public function store(Request $request)
{      
    $real = SpentTime::findOrCreate([
        'plan_id' => $request->get ('plan_id'),
        'daily_spent_time' => $request->get ('daily_spent_time'),
        'daily_percentage' => $request->get ('daily_percentage'),
        'reason' => $request->get ('reason')
    ]);

    return redirect()->route('real.index', compact( 'reals'));
}

this my model

public static function findOrCreate($plan_id)
{
    $real = SpentTime::find($plan_id);
    return $real ?: new SpentTime;
}

when I make data already in the database, the data is not updated.

Na Koriah
  • 75
  • 2
  • 3
  • 12

2 Answers2

3

Try like this

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save()
Parth kharecha
  • 6,135
  • 4
  • 25
  • 41
0

try this one

public function store(Request $request)
{      
    $real = SpentTime::findOrCreate($request->get('plan_id'),[
        'plan_id' => $request->get ('plan_id'),
        'daily_spent_time' => $request->get ('daily_spent_time'),
        'daily_percentage' => $request->get ('daily_percentage'),
        'reason' => $request->get ('reason')
    ]);

    return redirect()->route('real.index', compact( 'reals'));
}

public static function findOrCreate($plan_id,$data)
{
    $real = static::where('plan_id',$plan_id)->first();
    if (is_null($real)) {
        return static::create($data);
    } else {
        return $real->update($data);
    }
}
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57