【问题标题】:Laravel 5.7 validation makes nothingLaravel 5.7 验证无济于事
【发布时间】:2021-07-13 18:59:47
【问题描述】:

我的函数自己工作,但没有执行验证。有谁知道我忘了添加什么?

这是我的代码的 sn-p:

namespace App\Http\Controllers;

use App\Player;
use App\Tournament;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


    public function store(Request $request)
    {
       $data=$request->all();
$validator = Validator::make($data, [
            'first_name' => 'alpha|min:2|max:30',
        ]);
        
        
        
        if(Auth::check()){

            $foo = Foo::create([
                'first_name' => $request->input('fist_name'),
                'last_name' => $request->input('last_name'),
            ]);
 
            if($foo){
                return redirect()->route('foo.show', ['foo'=> $foo->id])
                ->with('success' , 'Foo created!');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Error when creating the foo');
    }

提前致谢

【问题讨论】:

  • dd($request);验证后请

标签: laravel validation laravel-5 laravel-validation


【解决方案1】:
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required',
        ]);

        //validating input

        if ($validator->fails()) {
            return back()->with('toast_error', $validator->messages()->all()[0])->withInput();
        }
// more code to run when if statement is executed with true for validated data
    } 

【讨论】:

    【解决方案2】:

    尝试不同的方法,例如:

    use Illuminate\Support\Facades\Validator;
    
    ...
    $data=$request->all();
    $validator = Validator::make($data, [
                'first_name' => 'alpha|min:2|max:30',,  
            ]);
    

    【讨论】:

    • 谢谢你!我更改了代码,但我知道函数的最后一部分存在问题。 if($data){ return redirect()->route('players.show', ['player'=> $data->id]) ->with('success' , 'Spieler erstellt'); }
    • 我无法理解你,但我的代码中缺少的部分即将检查验证,你可以通过以下方式做到这一点: if($validator->fails()){ return ERRORS } return ok
    • 对不起,我的意思是验证现在有效,但我的代码的最后一部分 if($data){ return redirect()->route('players.show', ['player'=> $data->id]) ->with('success' , 'player created'); } 将显示错误消息:尝试获取非对象的属性 'id'
    • 您当前的错误与问题无关。最好是作为新人发帖或在聊天中提问。
    • 保留 $foo 作为回报...通过 dd() 检查; $data的内容是什么,那不是你上面代码中的对象更新
    猜你喜欢
    • 2021-07-13
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    相关资源
    最近更新 更多