[英]Laravel 5.4 - form/API/view
I created an API ( store ) that saves the data on the database and returns 201 if successful or 404 if not. 我创建了一个API( store ),将数据保存在数据库中,如果成功则返回201,否则返回404。
if ($visit->save()){
$visit->view_visit = [
'href' => 'api/v1/visit/' . $visit->id,
'method' => 'GET'
];
$response = [
'msg' => 'Visit created.',
'visit' => $visit
];
return response()->json($response, 201);
}
$response = [
'msg' => 'Error during creation.'
];
return response()->json($response, 404);
It works perfectly. 它运作完美。 Using postman you can see that the status will be <<201 Created>>.
使用邮递员,您可以看到其状态为<< 201已创建>>。
This API should be used in two ways: called by another application or called by a Laravel form. 应该以两种方式使用此API:由另一个应用程序调用或由Laravel形式调用。 This is the question:
这是问题:
How do I call it in a way if it successful, it will load a given view on the browsers? 如果成功,我如何称呼它,它将在浏览器中加载给定视图? In other words, is there a way to make the form call a route (the api itself, something like ../api/visit/) and in case of success loads the other view?
换句话说,是否有一种方法可以使表单调用路由(api本身,如../api/visit/之类的东西),并在成功的情况下加载另一个视图? Also, I would like to pass the content of response['msg'] to this new view.
另外,我想将response ['msg']的内容传递给这个新视图。
I know I could do it inside the store method by filtering the HTTP referrer, but I would like to keep the controller code strictly to manage the record creation. 我知道我可以通过过滤HTTP引荐来源网址在store方法内完成此操作,但是我想严格保留控制器代码来管理记录创建。 Besides that, I have to send the 201/404 codes along with the returned data.
除此之外,我还必须发送201/404代码以及返回的数据。
I also considered creating another controller to handle the API response and then call the form, but it still sounds too much -- it's supposed to be easy, I guess. 我还考虑过创建另一个控制器来处理API响应,然后调用该表单,但听起来还是太多了-我猜这应该很简单。
In laravel you can use a helpful method which determines if the request that has been sent is an AJAX request or just a normal request, which is: 在laravel中,您可以使用一种有用的方法来确定已发送的请求是AJAX请求还是普通请求,即:
$request->wantsJson()
So, Inside your controller in the return function, you will make an if statement: 因此,在返回函数的控制器内部,您将执行一条if语句:
if ($request->wantsJson()) {
return response()->json();
}else{
return view(...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.