Laravel-尝试提交表单时出错

时间:2018-10-22 13:41:04

标签: php laravel

我有一个更新记录的表格,但是我收到以下错误:

  

方法App \ Handling :: __ toString()不得引发异常,捕获InvalidArgumentException:数据丢失

Handling是我的模型。

这是我的路线:

Route::get('/update-handling/{id}', 'HandlingController@edit');
Route::post('/update-handling/{id}', 'HandlingController@update')->name('postUpdateHandling');

get工作正常,并正确地向我返回了Handling对象。当我尝试更新表单并转到post路线时,会向我返回上述错误。

这是我的update函数:

    public function update(Request $request, $id)
    {
      $name = $request->input('name');
      $handling = $request->input('handling-thermic');

      $thermic = 0;
      $superficial = 0;

      if ($handling == 0)
      {
        $thermic = 1;
      }
      else if ($handling == 1)
      {
        $superficial = 1;
      }

      $handling = Handling::find($id);

      $handling->u_name = $name;
      $handling->u_thermic = $thermic;
      $handling->u_superficial = $superficial;
      $handling->u_active = 1;
      $handling->save();

    }

我的html表单:

{!! Form::open(['id' => 'update-handling', 'url' => route('postUpdateHandling',['id' => $handling->id]), 'method' => 'post']) !!}

1 个答案:

答案 0 :(得分:0)

您的表格应为:

    <form method="post" action="{{route('postUpdateHandling',['id'=>$handling->id])}}">
       ...

      <button type="submit">Submit</button>
    </form>

在您的控制器中:

 use Session;

 public function update(Request $request, $id)
    {
       // first find record exists or not , if exits then update else redirect to 404 or home page

      $handling = Handling::find($id);
      if($handling){

      $name = $request->input('name');

      // added ternary condition for better syntax 

      $thermic = (int)$request->input('handling-thermic')==0 ? 1 : 0 ;
      $superficial =(int)$request->input('handling-thermic')==1 ? 1 : 0 ;

      $handling->u_name = $name;
      $handling->u_thermic = $thermic;
      $handling->u_superficial = $superficial;
      $handling->u_active = 1;
      $handling->save();
       return redirect()->back()->with('success', 'Updated');          

      }else{
        // redirect to 404 or homepage
         return redirect('/home');
      }

    }

在刀片视图中,在以下片段中添加显示消息:

@if (session()->has('success'))
    <h1>{{ session('success') }}</h1>
@endif