Laravel学习笔记基础系列--(十二)Laravel响应相关操作

作者: 温新

分类: 【Laravel】

阅读: 1770

时间: 2021-07-10 05:25:50

作者:温新

时间:2021-06-27

一个用户请求被控制器中的方法处理完成之后,会发送一个响应组用户浏览器。对于实际开发中,如添加入库操作,处理完成之后一般会返回一个json格式的数据给浏览器,这就是响应。非常实用的是,我们可以直接返回一个数据,Laravel会自动将数组转为json返回组用户浏览器。

一个返回字符串的简单案例:

Route:;get('test', function(){
    return 'hello laravel';
});

实际中需要的返回可能不是这么简单,这就需要用到Response对象,Illuminate\Http\Response 实例。下面的演示将在DemoController中的index方法演示。

响应JSON数据

// 方式一
return response()->json(['code'=>200,'msg'=>'succ']);
// 方式二
return ['code'=>200,'msg'=>'succ'];

添加响应头

// 方式一
return response('添加响应头')
    ->header('Content-Type','text/plain')
    ->header('X-Header-One', 'Header Value');
// 方式二
return response('添加响应头')
    ->withHeaders([
        'Content-Type' => 'text/plain',
        'X-Header-One' => 'Header Value'
    ]);

添加cookie到响应头

return response()->json(['code'=>2000])->cookie('webName','自如初');

重定向

重定向操作使用得比较多,如非法访问需要登录后才能访问的页面,就可以使用重定向将其打回到登录页面。

基础重定向

方法:redirect

// 访问laravel欢迎页,重定向到添加界面
Route::get('/', function () {
    return redirect('/demo');
    // return view('welcome');
});

重订向上一个请求

方法:back

return back()->winthInput();

重定向到指定的命令路由

方法:route

// 改造路由
Route::get('demo', 'DemoController@index')->name('demo');

开始路由重定向

Route::get('/', function () {
    return redirect()->route('demo');
});

重定向携带参数

方式一:传递参数

// web.php
Route::get('/', function () {
    return redirect()->route('demo',['name'=>'李四']);
});
// index方法中可以使用 all()方法接收参数
dd($requst->all());

方式二:传递实例对象数据

// web.php
Route::get('/', function () {
    $user = \App\Models\User::find(1);
    return redirect()->route('demo',[$user]);
});

// 通过依赖注入接收数据
public function index(Request $request, \App\Models\User $user)
{
    dd($user);
}

重定向到控制器方法

方法:action

Route::get('/', function () {
    // 方式一
    return redirect()->action([\App\Http\Controllers\DemoController::class,'test']);
    // 方式二 携带参数
    return redirect()->action([\App\Http\Controllers\DemoController::class,'test'],['id'=>1]);
});

重定向到外部域名

方法:away

return redirect()->away('https://www.ziruchu.com');

携带一致性session数据的重定向

return redirect()->with('status', 'Profile updated!');

然后就可以在视图中使用了

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

文件下载

方法:download($filePath,$name,$headers)

参数一:要下载的文件路径;

参数二:下载文件显示的名称;

参数三:传递头信息

下面就用上篇文章上传的图片来做下载演示;

定义新的路由并提供下载

// web.php
Route::get('down', function() {
    return response()
        ->download(storage_path('/app/public/images/20210627212013.png'),'下载测试');
});

我是温新

每天进步一点点,就一点点

请登录后再评论