关于目录或文章不存在的报错代码

今天整理一天的部署上线没完成。不过晚上搞了一个目录或者文章报错代码。php

一、建立路由

直接将其建立在了Home前台indexController.php主页控制器上。css

Route::get('/errors/nothing','Home\indexController@nothing');

二、建立控制器

indexController.php文件中建立函数:html

public function nothing()
    {
        return view('errors.nothing');
    }

在建立函数后,先测试路由是否打通,打通后建立报错视图文件。数据库

三、创建报错模板

创建nothing.blade.php报错文件。api

<!DOCTYPE html>
<html>
    <head>
        <title>对不起,不存在!</title>

        <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

        <style>
            html, body {
                height: 100%;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                color: #B0BEC5;
                display: table;
                font-weight: 100;
                font-family: 'Lato';
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 72px;
                margin-bottom: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">对不起,不存在!</div>
            </div>
        </div>
    </body>
</html>

直接在地址栏中运行composer

blog/errors/nothing

显示运行正常。函数


四、建立中间件

利用composer建立中间件:测试

php artisan make:middleware CheckAge

建立完成后
撰写内容google

public function handle($request, Closure $next)
    {
        $_arti=Article::where('art_id',$request->art_id)->find($request->art_id);
        if (!$_arti){
            return redirect('errors/nothing');
        }
        return $next($request);
    }

五、在路由上增长中间件功能

Route::get('/a/{art_id}','Home\IndexController@article')->middleware('checkArt');

测试经过。code


六、后记

在建立中间件时候,确实测试了好多代码。
显示看网上如何判断空结果集。

即便取到的空结果集Eloquent仍然会返回IlluminateDatabaseEloquentCollection对象实例。这个我曾经也测试过,确实dd()测试以后含有结果集输出,只是输不了数据库中的字段内容,因此采用if()字段判断时,依然失效。

其实,Eloquent已经给咱们封装几个判断方法。

$result = Model::where(...)->get();
//不为空则
if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }

可是使用->get()显示这是一个无定义字段,后来发现find()可使用,具体缘由待好好看手册再分析。

参考:
在Laravel Eloquent 判断取出的结果集是否为空http://www.cnblogs.com/wuoshi...和Eloquent collection: counting and detect empty http://stackoverflow.com/ques...中代表:

相关文章
相关标签/搜索