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.

1

2 Answers 2

3

Try like this

$user = User::firstOrNew(array('name' => Input::get('name')));
$user->foo = Input::get('foo');
$user->save()
Sign up to request clarification or add additional context in comments.

4 Comments

in my controller ?
@NaKoriah yes you need to add this in your controller
nothing change. nothing to updated
this is laravel internal function you can read this here https://laravel.com/docs/5.7/eloquent#retrieving-single-models and find this firstOrCreate.
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);
    }
}

7 Comments

error errors
@NaKoriah check i updated my answer
@NaKoriah again u try
the error is Undefined variable: record
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.