控制器 StuController
<?php
namespace App\Http\Controllers\Stu;
use App\Http\Controllers\Controller;
use App\Http\Databases\Stu\Stu;
use App\Http\Traits\HasResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StuController extends Controller
{
public $rules = [
'name'=>'',
'sex'=>'',
'stunum'=>''
];
use HasResource;
public function index(){
$stus = DB::table('stu')->paginate(15);
return $stus;
}
public function store(Request $request)
{
$data = Stu::create($this->getStore());
return $this->success($data);
}
public function show(Request $request,$id)
{
$data = Stu::query()->findOrFail($id);
return $data;
}
public function update(Request $request ,$id){
$data = Stu::query()->find($id);
$this->setUpdateData($data);
$data->save();
return $data;
}
public function destroy(Request $request, $id)
{
$model = new Stu();
$data = $model->destroy($id);
return $data;
}
}
模型
<?php
namespace App\Http\Databases\Stu;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Http\Databases\BaseModel;
use Illuminate\Support\Facades\DB;
class Stu extends BaseModel
{
use SoftDeletes;
protected $table = 'stu';
protected $fillable = [
'id', 'name', 'sex', 'stunum','time'
];
public function show(){
return $this->get();
}
public static function boot(){
self::creating(function($model){
$model->stunum +=1;
$model->time = time();
});
}
}
数据库迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStuTable extends Migration
{
public function up()
{
Schema::create('stu', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->comment('姓名');
$table->string('sex')->comment('性别');
$table->string('stunum')->comment('学号');
$table->timestamps();
$table->softDeletes();
});
}
public function down()
{
Schema::dropIfExists('stu');
}
}
路由
路由 web.php
$router->group(['namespace' => 'Stu', 'prefix' => 'test'], function ($router) {
$router->resource('stu', 'StuController');
});
注:如果需要自定义控制名字使用$router->put('stu/{id}','StuController@upStu');
简单的使用增删改查,在路由中使用$router->resource('stu', 'StuController');
protected $fillable = [
'id', 'name', 'sex', 'stunum','time'
];
只有在白名单的才不会被过滤
|