【问题标题】:Using RedirecResponse outside Laravel在 Laravel 之外使用 RedirecResponse
【发布时间】:2015-07-27 15:34:32
【问题描述】:

我正在连接我的外部应用程序以在 Laravel 5 中执行一些操作,获得响应并继续。其中一项操作是登录使用 Laravel 代码:

在 Laravel 之外

<?php
use Laravel\Laravel;

# Some code here but not headers or html output
Laravel::login();

# Another some code more and then print login form from laravel blade template
echo Laravel::loginView();

Laravel 自定义连接类(在 Laravel 之外)

<?php
namespace Laravel;

use App;
use Illuminate;

class Laravel
{
    private static $app;

    private static function load()
    {
        require_once self::getPath('bootstrap/autoload.php');

        self::$app = require_once self::getPath('bootstrap/app.php');

        self::$app->make('Illuminate\\Contracts\\Http\\Kernel')->handle(Illuminate\Http\Request::capture());
    }

    public static function login()
    {
        self::load();

        $response = App::make('App\\Http\\Controllers\\User')->login($_POST);

        if ($response instanceof RedirectResponse) {
            # Here I want to stop my app, save cookies/headers from Laravel Login
            # and redirect to $response target url location
            # If I do it with a simple Location redirect, I lost cookies and headers
            # and User will be not authenticated on next request
            die($response);
        }
    }

    public static function loginView()
    {
        self::load();

        return view('pages.users.login');
    }
}

Laravel 应用\Http\Controllers\User@login

class User
{
    public function login($data)
    {
        $success = Auth::attempt([
            'user' => $data['user'],
            'password' => $data['password'],
        ], $data['remember']);

        if ($success) {
            return redirect()->to(url('/'));
        }
    }
}

我的所有代码都可以正常工作(查看模板、用户验证、登录),但最后我需要重定向登录响应,并带有标题和 cookie,以便在下一次请求时可用。

有没有简单干净的方法呢? (代码比较多,这里简化了)

非常感谢:)

【问题讨论】:

    标签: php session laravel


    【解决方案1】:

    有一种简单而干净的方法可以做到这一点,我来这里是为了做同样的事情,this page 向我展示了只需在响应中添加对-&gt;send() 的调用将发送响应时间>。在您的情况下,login 方法可能如下所示:

    public function login($data)
    {
        $success = Auth::attempt([
            'user' => $data['user'],
            'password' => $data['password'],
        ], $data['remember']);
    
        if ($success) {
            $response = redirect()->to(url('/'));
            $response->send();
            return $response;
        }
    }
    

    如果您的集成中有一个地方调用控制器方法,那么将调用放在那里会更有意义,这样您实际上就不会从控制器内部调用 -&gt;send()(因为 Laravel 没有t)。

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2015-11-10
      相关资源
      最近更新 更多