web.php
Route::group(['prefix'=> 'api'],function(){
Route::get('/user/{id}/{method}', function ($id) {
$user = App\User::find($id);
return new App\Http\Resources\User($user);
});
Route::get('/users/{method}',function(){
$users = App\User::all();
return new App\Http\Resources\UserCollection($users);
});
});
User.php
class User extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
private $status = 'success';
private $code = 200;
public function toArray($request)
{
if(method_exists($this, $request->method) && $method = $request->method){
return $this->$method();
}
$this->status = 'failed';
$this->code = '404';
}
public function getUser(){
return [
'username' => $this->name,
];
}
public function getUserEmail(){
return [
'username' => $this->email,
];
}
public function with($request){
return [
'status' => $this->status,
'code' => $this->code,
];
}
}
UserCollection.php
class UserCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
private $status = 'success';
private $code = 200;
public function toArray($request)
{
if(!method_exists(User::class, $request->method)){
$this->status = 'urlNotFound';
$this->code = '404';
return [];
}
return parent::toArray($request);
}
public function with($request){
return [
'status' => $this->status,
'code' => $this->code,
];
}
}
这个应该可以解决问题