【问题标题】:Redirect to page when value is null in another table laravel当另一个表中的值为空时重定向到页面 laravel
【发布时间】:2017-12-19 09:14:38
【问题描述】:

如果我的 additional_infos 表包含一些在这种情况下为空的内容,如联系人、姓名和地址,我会尝试将用户重定向到另一个页面。

我现在已经做过类似的事情了:

但即使填写了联系人、姓名和地址,它也会不断将我重定向到另一个页面。有人能帮我吗?提前致谢

public function test(Request $request){
    $additional_info = DB::table('additional_infos') ->where('address',NULL)->orWhere('name', NULL)->orWhere('number')->get();
    //request input //ignore this part
    if( $additional_info) {
        return redirect(url('/user/showupdate6/'.$id->id.'/edit6') );
    } else {
        return redirect('/home');
    }
}

如果填写了我的数据名称、联系人和地址,我希望它将我重定向到主页。如果我的数据名称、联系人和地址为空,我希望它将我重定向到此 URL,url('/user/showupdate6/'.$id->id.'/edit6')

【问题讨论】:

    标签: php laravel redirect


    【解决方案1】:

    你永远不会得到 null 以便你可以测试它,如果像这样 if( $additional_info) 它会一直评估为 true,因为即使没有满足的元素,它也会始终返回一个集合条件它将返回一个不为空的空集合。

    你有三个选择:

    • 使用->get()并在if语句中添加->count()if($additional_info->count())

    • ->get() 替换为->first() 并保留if($additional_info)

    • ->get() 替换为->count()if($additional_info > 0)

    像这样使用whereNullorWhereNull 试试:

    public function test(Request $request){
        $additional_info = DB::table('additional_infos') 
                                ->whereNull('address')
                                ->orWhereNull('name')
                                ->orWhereNull('number')
                                ->get();
        //request input //ignore this part
        if( $additional_info->count())
            return redirect(url('/user/showupdate6/'.$id->id.'/edit6') );
        else{
        return redirect('/home');
    }
    

    【讨论】:

    • 它仍然将我重定向回 showupdate url 部分......当它应该是 home url 时。我在 if else 语句部分做错了吗?
    • 在 if 语句中使用 ->count() 尝试我的最后一次更新
    • 您能解释一下为什么我必须在这种情况下使用 count 吗?我不太明白
    • 哦,我现在明白了。非常感谢您的帮助:)
    • 乐于助人 :) 我忘了添加另一种方法是用->first() 替换->get() 并留下if($additional_info) 它也可以工作,请参阅编辑;)
    【解决方案2】:

    尝试将您的查询转换为 SQL,以首先检查您对数据库的操作

    $additional_info = DB::table('additional_infos')->where('address',NULL)->orWhere('name', NULL)->orWhere('number')->toSql();
    dd($additional_info);
    

    【讨论】:

    • "select * from additional_infos where address is null or name is null or number is null" 这是返回
    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多