Home > Software engineering >  Update record using laravel
Update record using laravel

Time:08-03

I have a question, I have a form (view) and after submit it saves to the db. one of the records is id. when I open the form again for that ID and will press submit again what will happened it will update the record? or try to create a new record and fail since id is primary key?

CodePudding user response:

so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing

CodePudding user response:

public function store(Request $request)
    {
        $this->validate($request,[
            'name' => 'required|unique:categories',
        ]);

        $category = new Category();
        $category->name = $request->name;
        $category->slug = str_slug($request->name);
        $category->save();
        Toastr::success('Category Successfully Save','Success');
        return redirect()->route('admin.category.index');

    }

CodePudding user response:

If you're trying to update record based on it's id then you could do this

public function update($request)
{
    $user = User::firstOrNew([
                'id' => $request->id
            ]);
    $user->first_name = $request->first_name;
    $user->last_name = $request->last_name;
    $user->save();
}

It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.

  • Related