*修改資料:
*route:
routes\web.php
Route::get('/update_view/{id}', 'GameController@update_view');
Route::post('/update_view/{id}', 'GameController@update_view');
Route::post('/update/{id}', 'GameController@update');
-----------------
*view:
1.resources\views\game\update.blade.php
<!DOCTYPE html>
<html>
<body>
<h3>通訊錄</h3>
<p>修改資料:</p>
<form action="{{url('update/'.$games->id)}}" method="POST">
@csrf
<p>姓名:<input type="text" name="name" value="@if(old('name')!==null){{old('name')}}@else{{$games->name}}@endif"> {{ $errors->first('name') }}</p>
<p>電話:<input type="text" name="phone" value="@if(old('phone')!==null){{old('phone')}}@else{{$games->phone}}@endif"> {{ $errors->first('phone') }}</p>
<input type="submit" value="送出">
</form>
<br>
<a href="{{url('game')}}">回首頁</a>
</body>
</html>
2.resources\views\game\index.blade.php
<!DOCTYPE html>
<html>
<body>
<h3>通訊錄</h3>
@foreach ($games as $game)
<p>
{{ $game->id.'. '.$game->name .' : '. $game->phone }}
<form action="{{url('game/'.$game->id)}}" method="POST">
@csrf
@method('DELETE')
<input type="submit" value="刪除">
</form>
<form action="{{url('update_view/'.$game->id)}}" method="POST">
@csrf
<input type="submit" value="修改">
</form>
</p>
@endforeach
<br>
<p>新增資料:</p>
<form action="{{url('/insert')}}" method="POST">
@csrf
<p>姓名:<input type="text" name="name" value="{{ old('name') }}"> {{ $errors->first('name') }}</p>
<p>電話:<input type="text" name="phone" value="{{ old('phone') }}"> {{ $errors->first('phone') }}</p>
<input type="submit" value="送出">
</form>
</body>
</html>
-----------------
*controller:
app\Http\Controllers\GameController.php
//修改資料介面
public function update_view($id)
{
$games=Game::find($id); //查詢資料
return view('game.update',['games'=>$games]);
}
//修改資料
public function update(Request $request,$id)
{
//資料驗證
$validated=Validator::make(
$request->all(),
[
'name'=>'required|min:3',
'phone' => 'required|min:3',
],
[
'name.required'=>'請填寫姓名',
'name.min'=>'姓名最少3個字',
'phone.required'=>'請填寫電話',
'phone.min'=>'電話最少3個字',
]
);
//驗證失敗
if ($validated->fails()) {
return redirect('update_view/'.$id)
->withErrors($validated)
->withInput();
}else{
$game=Game::find($id);
$game->name=$request->name;
$game->phone=$request->phone;
$game->save();
return redirect('game');
}
}
沒有留言:
張貼留言