Get the data of a JsonResponse

0

I have a controller that accesses the method searchUserByName of another controller and returns a JsonResponse , this variable $user I understand that it is a Json right? If I want to get the value of the result that is inside, how should I do it?

    /**
 * @param Request $request
 * @return JsonResponse
 */
public function uploadSubmit(Request $request)
{

    foreach($request->file('file') as $file){
        try {
            ...
            ...
            $user = app('App\Http\Controllers\UserController')
                ->searchUserByName($attributes['name']);

        }
        catch (\Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

    /**
 * @param $name
 * @return Response
 */
public function searchUserByName($name)
{

    try {
        $user = User::where('name', 'like', '%'.$name.'%')->get();
    }
    catch (\Exception $exception) {
        return response()->json([
            'errors' => ['Error'],
        ], 500);
    }


    return new JsonResponse([
        'data' => $user,
    ]);
}
    
asked by ilernet 26.02.2018 в 11:34
source

1 answer

1

What you need to do to return $user is return $user . And $user is an object.

public function searchUserByName($name)
{

    try {
        $user = User::where('name', 'like', '%'.$name.'%')->get();
        return $user;
    }
    catch (\Exception $exception) {
        return response()->json([
            'errors' => ['Error'],
        ], 500);
    }

But beware, as you have any user called "manolo" or "manuel" will be found with the search string "man" and then return a collection . To find a user with an exact text and only return a record it should look like this:

public function searchUserByName($name)
    {

        try {
            $user = User::where('name', '=', $name)->first();
            return $user;
        }
        catch (\Exception $exception) {
            return response()->json([
                'errors' => ['Error'],
            ], 500);
        }

In the case of wanting to return a jSon, the output would be the following:

return $user->toJson();
    
answered by 26.02.2018 / 12:13
source