Happy Arif
Happy Arif

Reputation: 77

Laravel store and update data in store methods

Hello Senior Stack Guys, I have building simple forum posting website using laravel. There i have form field that make admin from admin panel it was dynamic system build by me.

Now what i am facing issue, When i print that field into user dashboard, I want them fillup that form with their own data and if its in database by this user it will update or it will store. you can see small screenshot here https://prnt.sc/hu3Ni7kBudmB.

Bellow what i got response after submit form:

<input type="text" class="form-control" name="field_{{$field->id}}" id="">

{
  "_token": "bGCaGoDbKHBnGtoUfMxzo3mBtCYZ132zPiUoTZBD",
  "user_id": "6",
  "group_id": "19",
  "field_1": null,
  "field_id": "53",
  "field_9": null,
  "field_10": null,
  "field_13": null,
  "field_15": null,
  "field_16": null,
  "field_11": "Salman Khan",
}

And My database is:

    $table->bigIncrements('id');
    $table->text('value')->nullable();
    $table->bigInteger('group_id')->unsigned();
    $table->bigInteger('field_id')->unsigned();
    $table->bigInteger('user_id')->unsigned();

I have a lot of field, so I want if field id dont have in that user it will be store else the request data need to be updated

Here is my controller file:

$group_check = $request->group_id;
$field_check = ProfileField::where('id', $request->field_id)->first();

if( !empty($field_check) )
{
    return $request->all();
}
else
{
    return "Update Action";
}

Upvotes: 1

Views: 607

Answers (1)

Irvan Rifa&#39;i
Irvan Rifa&#39;i

Reputation: 81

You can use updateOrCreate() method, if data from request that id is exist in database, method will execute update data. if data not exist method will execute create new data.

$group_check = $request->group_id;
$field_check = ProfileField::where('id', $request->field_id)->first();

if( !empty($field_check) )
{
    return $request->all();
}
else
{
    return ProfileField::updateOrCreate($request->all());
}

I hope it helps you :)

Upvotes: 2

Related Questions