Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 数据库中是否存在名称?拉维尔_Php_Mysql_Database_Laravel_Exists - Fatal编程技术网

Php 数据库中是否存在名称?拉维尔

Php 数据库中是否存在名称?拉维尔,php,mysql,database,laravel,exists,Php,Mysql,Database,Laravel,Exists,我有一个名为categories的数据库表,在该表中我有字段: id,name,description和urlname 我想在route.php文件中检查url是否正确: Route::get('products/{cat}' ,function($cat){ $objCat = new Category; if($objCat-> ??? ){ return View::make('products')->with('cat', $cat);

我有一个名为
categories
的数据库表,在该表中我有字段:
id
name
description
urlname

我想在
route.php
文件中检查url是否正确:

Route::get('products/{cat}' ,function($cat){
    $objCat = new Category;

    if($objCat-> ??? ){
        return View::make('products')->with('cat', $cat);
    }else{
        return View::make('notfound')->with('cat', $cat);
    }
});
如何使用
检查
类别
表中的
urlname
字段中是否存在
$cat
变量


谢谢

不要实例化类别对象。 您可以执行以下操作:

$model = Category::where('id', '=', $cat)->firstOrFail();
并使用重定向注册异常

use Illuminate\Database\Eloquent\ModelNotFoundException;

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

这里还有一篇关于laravel中错误处理的文章:

这将满足您的要求:

Route::get('products/{urlName}', function ($urlName) {
    $objCat = Category::where('urlname', $urlName)->first();
    if ($objCat)
         return View::make('products')->with('cat', $objCat);
    else
         return View::make('notfound')->with('cat', $objCat);
});

一些编程风格的建议。。。我建议避免使用缩写,以使代码更清晰(“类别”而不是“cat”)。我还建议使用控制器,而不是将代码放在routes.php的function()块中。这将帮助您更好地组织代码并保持routes.php文件的简单性,但也允许您使用路由缓存。

您能否给出一个
route.php
文件的示例,因为现在我遇到了路由结构的问题。这并不是OP想要的,因为他们想要返回一个名为“notfound”的特殊视图,用于找不到类别的特殊情况。