PHP笔记-laravel框架记录session中flash()的一次应用

x33g5p2x  于2022-06-16 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(238)

场景说明

我这里有个表单提交页面,他的url是get方法/hasLogoIndex。表单提交是post方法/hashLogoSubmit,提交表单后,验证各个参数是否正确,调用三方http的API,得到结果,然后回给/hasLogoIndex页面。也就是重定向到表单提交页面,并且有些图片方面的提示,也在那个页面显示,这里就可以使用flash了。

具体代码

表单页面函数:

public function index(Request $request){

    if($request->session()->exists('hashModel')){

		return view('hashLogo.index')->with('hashModel', $request->session()->get('hashModel'));
    }
    return view('hashLogo.index');
}

表单提交函数:

public function submit(Request $request){

    $this->validate($request, [
        'inputString' => 'required|min:6|max:128',
        'logoType' => 'required'
    ]);

    $type = 32;
    if($request->logoType == 'logo64'){

		$type = 64;
    }
    else if($request->logoType == 'logo128'){

        $type = 128;
    }
    else{

    }

    $hashModel = null;
    $client = new Client();
    try {
        $res = $client->request('GET', 'http://127.0.0.1:8889?string=' . $request->inputString . "&type=" . $type);
        $jsonObject = json_decode($res->getBody()->getContents());
        $hashModel = new HashModel($jsonObject->img, date('Y-m-d h:i:s', time()), $type);
    }catch (GuzzleException $e) {

        return redirect()->route('hashLogoIndex');
    }

    $request->session()->flash('hashModel', $hashModel);

    return redirect()->route('hashLogoIndex');
}

原理:

submit中通过$request->session()->flash()把参数写入,这个flash相当于一次性的。取出后就无用了。

index中先看session中有没有flash指定的key,如果有,就说明这个是重定向来的,就把数据给blame前端,然后展示。如果没有就不用传这个参数了。

相关文章

微信公众号

最新文章

更多