Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the update method in laravel 5.4 crud?

Tags:

php

laravel

crud

i just trying to crud system. for that into controller store function my code is

 public function store(Request $request)
{
    Article::create([
        'user_id' => auth()->id(),
        'content' => $request->content,
        'live' => (boolean)$request->live,
        'post_on' => $request->post_on
        ]);

    return redirect('/articles');
}

it's enough to store data, but when i want to edit article & save again then what will be my edit function code? i have no idea. i trying same code into edit function & it create new article not update. so what will be right code for edit function? thanks

like image 992
Masum Avatar asked Dec 02 '22 11:12

Masum


2 Answers

Resource controller method for update is update(). Eloquent method for update() is update() too, so you can do this:

public function update(Request $request, $id)
{
    Article::where('id', $id)->update($request->all());
    return redirect('/articles');
}

You also can use the same controller and Eloquent method for both crerate and update data updateOrCreate() method.

like image 107
Alexey Mezenin Avatar answered Dec 06 '22 00:12

Alexey Mezenin


You can also update it as object format like this.

public function update(Request $request, $id)
{
   $article = Article::find($id);
   $article->user_id = auth()->id();
   $article->content = $request->content;
   $article->live = (boolean)$request->live;
   $article->post_on = $request->post_on;
   $article->save();
}`
like image 30
Sami Avatar answered Dec 06 '22 00:12

Sami