【发布时间】:2017-08-22 13:01:39
【问题描述】:
我是一名初级 PHP 开发人员,我正在使用 Laravel 5.4 框架实现 CRUD,到目前为止一切正常。
但我当时试图让这段代码在网站和移动设备中也能正常工作,所以我了解了 Web 服务和它的协议,如 Rest、Soap,我成功地与他们合作并为自己构建了小型脚本学习,事情会变得更好。
当我尝试在我的 CRUD 上应用我学到的东西时,我卡住了,没有链接可以通过路由和 api.php,web.php 文件来构建我的代码,我不知道在哪里构建我的服务器或客户端脚本以及如何在 laravel 中链接它们,即使我设法在本机 php 中实现了这一点,但是在 laravel 中我有点困惑我上网并发现实际上对我没有任何用处..
我将在(创建新用户函数)上提供我的简单 CRUD 代码。希望有人可以帮助我或让我走上正轨,开始在不同的项目中使用这种技术。
我的控制器
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class AddController extends Controller
{
public function create(){ //create new user page
return view('add.create');
}
public function store(){ //store new user added by a clint
$this->validate(request(), [ //validation for request records
'name' => 'required',
'email' => 'required',
'password' => 'required|min:8',
'password_confirmation' => 'required|same:password'
]);
$user = User::create([ //create new user with the request records
'name' => request('name'),
'email' => request('email'),
'password' =>bcrypt(request('password'))
]);
session()->flash('message','Changes has been Applied'); //flash a succcess message
return redirect()->home(); // redirect to home after submitting the new user
}
}
我的路线(不是资源路线,只是原生路线)
// add new user routes
Route::get('add','AddController@create')->middleware('authenticated');
Route::post('add','AddController@store');
我的模特
是 laravel 提供的 Built-In User.php 模型。
我的视图 add.create.blade.php
<!-- this is the view of the add new user tab , extending master layout and it's components-->
@extends('layouts.master')
@section('content')
<div class="col-md-8">
<h3>Enter the Values of the new User</h3>
<form method="POST" action="add">
{{csrf_field()}}
<div class="form group">
<label for="name">*Name:</label>
<input type="name" class="form-control" id="name" name="name">
</div>
<div class="form group">
<label for="Email">*Email Address:</label>
<input type="email" class="form-control" id="email" name="email">
</div>
<div class="form group">
<label for="password">*Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="form-group">
<label for="password confirmation">*Confirm Password:</label>
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation" >
</div>
<br>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add User</button>
</div>
@include('layouts.errors')
</form>
</div>
@endsection
这就是我到目前为止所达到的,我希望如果有人告诉我如何将 api 应用于此代码以使其也能在移动设备上运行,我真的很感谢提前提供任何帮助。
【问题讨论】:
-
您也可以使用自动 API 方法/库,而不是自己完成所有艰苦的工作。 PHP-CRUD-API(有 2k github 星)可以轻松加载和配置,如 here 所述。注意:我是那篇文章的作者。
标签: php laravel web-services api