laravel框架實現數據的刪除和修改
//模型層的調用
<?php
namespace App;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class teach extends Model
{
//數據表
public $table=‘teach‘;
//定義主鍵
public $primarkey=‘id‘;
//時間戳
public $timestamps=true;
//白名單
protected $fillable=[‘updated_at‘,‘created_at‘,‘name‘,‘sex‘,‘tel‘,‘id‘];
}
//展示頁面
<a href="{{ route(‘teach.edit‘, $teacher->id ) }}">Edit</a>//跳轉修改方法
<form action="{{ route(‘teach.destroy‘, $teacher->id) }}" method="post" style="display: inline-block;">
{{ csrf_field() }}
{{ method_field(‘DELETE‘) }}
<button type="submit" style="color: #F08080;background-color: transparent;border: none;">Delete</button>//跳轉刪除方法
</form>
<?php
namespace App\Http\Controllers;
use App\School;
use App\teach;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TeachController extends Controller
{
//引入修改頁面
public function edit($id)
{
$teacher = Teach::findOrFail($id);
return view(‘teachers.edit‘, compact(‘teacher‘));
}
edit.blade.php:
@extends(‘layouts.app‘)
@section(‘content‘)
<form action="{{ route(‘teach.update‘, $teacher->id) }}" method="post">
{{ csrf_field() }}
{{ method_field(‘PATCH‘) }}
<!-- //這是跨站方法偽造,HTML 表單沒有支持 PUT、PATCH 或 DELETE 動作。所以在從 HTML 表單中調用被定義的 PUT、PATCH 或 DELETE 路由時,你將需要在表單中增加隱藏的 _method 字段來偽造該方法
-->
<label>姓名:</label>
<input type="text" name="name" style="width:100%;" value="{{ old(‘name‘) }}">
<label>性別:</label>
<input name="sex" rows="10" style="width:100%;" value="{{ old(‘sex‘) }}">
<label>電話:</label>
<input name="tel" rows="10" style="width:100%;" value="{{ old(‘tel‘) }}">
<button type="submit">OK</button>
</form>
@endsection
//修改
public function update(Request $request, $id){
$this->validate($request, [
‘name‘ => ‘required|max:50‘,
]);
$teacher = Teach::findOrFail($id);
$teacher->update([
‘name‘ => $request->name,
‘sex‘ => $request->sex,
‘tel‘ => $request->tel,
]);
}
//刪除
public function destroy($id)
{
$teacher = Teach::findOrFail($id);
$teacher->delete();
return back();
}
laravel框架實現數據的刪除和修改