Laravel Eloquent - 检查返回的对象是否有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25315301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:56:49  来源:igfitidea点击:

Laravel Eloquent - checking if returned object is valid or not

phplaraveleloquent

提问by StackOverflowed

I'm retrieving objects using Laravel's Eloquent, and I'm trying to see if the object is valid or not.

我正在使用 Laravel 的 Eloquent 检索对象,并试图查看该对象是否有效。

For instance

例如

$user = User->where('first_name', 'Adam')->first(); // what if there are no Adams?

$user = User->where('first_name', 'Adam')->first(); // what if there are no Adams?

I get a Builder object when there are no Adams and a User object when there is. Without using instanceof, is there a way to find out if the object returned is a valid User? Ideally, Eloquent would have just returned a null or some InvalidObject object as a response.

当没有 Adams 时我得到一个 Builder 对象,当有一个 User 对象时。不使用instanceof,有没有办法确定返回的对象是否是有效用户?理想情况下,Eloquent 会返回一个 null 或一些 InvalidObject 对象作为响应。

回答by Razor

firstmethod return nullif a model is not found, you may also use firstOrFailmethod to throw an exception

firstnull如果没有找到模型,方法返回,您也可以使用firstOrFail方法抛出异常

回答by Mark Baker

If there are no matches for your query, then $user should be a falsey value

如果您的查询没有匹配项,则 $user 应该是一个 falsey 值

    if (!$user) {
        App::abort(404, 'User record does not exist');
    }

回答by Rashi Goyal

This worked for me hope it help others I tried this and it worked for me

这对我有用希望它可以帮助其他人我尝试过这个并且对我有用

$model = Leadset::where('name',$data['name'])->first();
if(!$model) echo "no name found";