如何在laravel控制器中调用函数后返回数组

时间:2017-05-10 07:19:59

标签: php laravel return laravel-5.4 function-calls

我正在使用laravel。我的UserController调用一个公共函数(validateToken),它位于控制器的顶部。我从另一个公共函数调用我的函数,但这不会返回任何东西。 这是我的代码:

use App\Comment;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function validateToken($token)
    {
        $user = User::where('token', $token)->first();

        if(!isset($user))
        {
            return array(
                'message' => "These credentials do not match our records.",
                'success' => false
                };
        }
    }

    public function register(Request $request)
    {
        $input = Input::all();

        $this->validateToken($input['token']);

        return array(
            'message' => 'Your account has been created successfully and is ready to use', 
            'token'   => $input['token'], 
            'success' => true
           );
    }

如果validateToken代码放在​​寄存器函数

中,它就有效

2 个答案:

答案 0 :(得分:0)

您从其他类调用哪种方法?

无论如何,

validateToken()应该在分开的课堂上。将其放置在用户模型中,如:

// \App\User model
public static function isValidToken($token)
{
    $user = self::where('token', '=', (string)$token)->first();

    return [
        'success' => $user !== null,
        'message' => $user === null
            ? 'These credentials do not match our records.'
            : 'User found, token is valid',
    ];
}

现在,您可以通过以下方式从Laravel应用程序的任何位置访问此方法:

$check_token = User::isValidToken('my-token');

答案 1 :(得分:0)

您应该在调用该函数后处理返回值。

use App\Comment;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function validateToken($token)
    {
        $user = User::where('token', $token)->first();

        if(!isset($user))
        {
            return array(
                'message' => "These credentials do not match our records.",
                'success' => false
                };
        }else {
            return array(
                'message' => 'Your account has been created successfully and is ready to use', 
                'token'   => $token, 
                'success' => true
               );
        }


    }

    public function register(Request $request)
    {
        $input = Input::all();

        return $this->validateToken($input['token']);

    }
}