首页 > 解决方案 > 比较控制器上的字符串

问题描述

我有一个包含 2 个项目(胡萝卜和柠檬)的下拉列表。我想Carrot比较Lemon。如果它是蔬菜,则添加被验证,否则它会在表单中被阻止。

在此处输入图像描述

在我的代码中,验证不正确...我的 2 个值通过...

在此处输入图像描述

public function store(Request $request)
    {
        $this->validate($request, [
                'vegetables' => 'required|min:3'
        ]);

        $listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count();

        $word = "Carrot";

       if ($listVegetable == $word){
            Exo::create($request->all());
            return redirect()->route('exos.index')
                ->with('success', 'new data created successfully');
        }

        else{
            return redirect()->route('exos.index')
                ->with('error', 'Not vegetable');

        }  
    }

标签: phpstringlaravellaravel-validation

解决方案


随着$listVegetable = Exo::where('vegetables', $request->get('vegetables'))->count();您将数据库中的蔬菜数量作为整数值。因此,您与carrot字符串的比较没有意义。你应该写first()而不是count()然后我猜你需要访问这个对象的 ->name 属性,这取决于你的模型有哪些行。


推荐阅读