Laravel - 如何处理控制器中的 API 响应?

Laravel - How to handle API response in controller?

我在电子商务网站上工作

1-这是后台工程中的函数..

public function register(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'password' => 'required',
        'mobile' => 'required|unique:users',
        'country_id' => 'required'
    ]);
    if ($validator->fails()) {
        return response()->json(['error'=>$validator->errors()], 401);
    }
    $input = $request->all();
    $input['password'] = bcrypt($input['password']);
    $user = User::create($input);
    $success['token'] =  $user->createToken('MyApp')-> accessToken;
    $success['name'] =  $user->name;
    return response()->json([
        'status' => 'success',
        'data' => $success,
    ], 200);    

}

2- 这个函数来自客户端。

protected function register(Request $request)
{
    $response = \Curl::to('http://localhost/backend/public/api/v1/client-register')->withData(
        [
            'name'=> $request->name,
            'email'=> $request->email,
            'password'=> $request->password,
            'mobile'=>$request->mobile,
            'role_id'=>5,
            'country_id'=> $request->country_id
        ])->post();

        $data = json_decode($response, true);

        // what i need here 

        /*check if(response success){

            / go to route('bla bla');

        }else{

            return back with msg 
            please help 
        }**/

}

**请帮忙:我需要处理响应,如果成功则转到路线A,如果失败则返回消息!

你的代码应该是这样的。

protected function register(Request $request)
{
    $response = \Curl::to('http://localhost/backend/public/api/v1/client-register')->withData(
        [
            'name'=> $request->name,
            'email'=> $request->email,
            'password'=> $request->password,
            'mobile'=>$request->mobile,
            'role_id'=>5,
            'country_id'=> $request->country_id
        ])->post();

        $data = json_decode($response, true);

        if(isset($data['status'])) {
            return redirect()->route('bla bla');
        } 

        return redirect::back()->withErrors($data['error']);

}