i need an explanation about how this update code works (Laravel)

时间:2018-12-03 12:58:21

标签: laravel

public function editCategory(Request $request,$id = null){//we pass the $id
    if($request->isMethod('post')){
        $data = $request->all();
        Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
            'description'=>$data['description'],'url'=>$data['url']]);
        return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully');
    }

    $categoryDetails = Category::where(['id'=>$id])->first();  return view('admin.categories.edit_category')->with(compact('categoryDetails'));

} //this code is working in my controller

3 个答案:

答案 0 :(得分:0)

ok i will explain to you this is edit fonction so it make modification of data stored in database

if($request->isMethod('post')){//if your data submitted to database
        $data = $request->all();//recupration of all information
        Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
            'description'=>$data['description'],'url'=>$data['url']]);//change description , categoryname and url
        return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully')//and return seccess alert in your view;
    }

    $categoryDetails = Category::where(['id'=>$id])->first();  return view('admin.categories.edit_category')->with(compact('categoryDetails'));

答案 1 :(得分:0)

public function editCategory(Request $request,$id = null){//we pass the $id
//check that the request is a POST request
if($request->isMethod('post')){

    //Okay so it is, now store all request parameter in it's own variable
    $data = $request->all();

    //Access the Eloquent model Category, checks the id and updates 
    //accordingly
    Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
        'description'=>$data['description'],'url'=>$data['url']]);

    //Return redirect to view-categories with a success message
    return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully');
}

//check the first id and return the view with the details, this would only be hit if the above if statement wasn't (wasn't a POST request for example)
$categoryDetails = Category::where(['id'=>$id])->first();  return view('admin.categories.edit_category')->with(compact('categoryDetails'));

答案 2 :(得分:0)

有两种方法可以调用此操作:

  • HTTP POST方法中的请求

    如果您使用HTTP /admin/edit-category/12345方法对URL POST进行请求 然后您用Category更新名为id = $id的模型(在我的示例中 $ id为12345),然后您将在Flash中重定向到/admin/view-categoriesCategory Updated Successfully

  • 增值的消息变量
  • 使用HTTP GET方法请求(或任何其他HTTP方法)

    如果您使用HTTP /admin/edit-category/12345方法对URL GET进行请求,则该操作将以模型Categoryid = $id(在我的示例中为$ id为12345),并将模型的字段放在视图参数中。