如何在laravel中输入会话代码号?

时间:2019-06-08 21:28:12

标签: php laravel laravel-5.8

注册后重定向到此页面。

我要输入此代码。 (当然,手机号码和代码会保存在数据库中并向手机发送短信)。

如何输入会话代码编号?

Code

web.php

Route::get('/code', 'HomeController@code')->name('code');
Route::post('/send', 'HomeController@send')->name('send');

RegisterController.php

public function register(Request $request, User $user)
{
    $code = rand(10000,99999);
    $user = \App\User::create([
        'first_name' => $request->first_name,
    .
    .
    .
    .
return redirect()->route('code',['mobile'=>$request->mobile]);

HomeController.php

public function code()
{
    return view('Home.send');
}

    public function send(Request $request)
{
    $mobile = $request->session()->get('mobile');
    $user = User::whereCode($request->code)
        ->whereMobile($mobile)
        ->firstOrFail();
    if($user){
        $user->verification_code = 1;
        $user->save();
        alert()->success('ok');
        return redirect()->back();
    } else {
        alert()->error('error');
        return redirect()->back();
    }
}

send.blad,php

<form action="{{ route('send') }}" method="post">
    {{ csrf_field() }}
    <div class="form-group">
        <label for="code">Code</label>
        <input type="text" class="form-control" name="code" id="code">
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
    </div>
</form>

我收到此错误

404

我在verification_code表中有users。我想在输入真实代码和手机号码的情况下,verification_code更改为1

1 个答案:

答案 0 :(得分:0)

看看Retrieving Single Models - Not Found Exceptions

  

firstOrFail方法将检索查询的第一个结果;   但是,如果未找到结果,   Illuminate \ Database \ Eloquent \ ModelNotFoundException将被抛出。

     

如果未捕获到异常,则会自动发送404 HTTP响应   回到用户。不必向   使用这些方法时,会返回404响应。

因此,您可以尝试捕获该异常:

try {
    $mobile = $request->session()->get('mobile');
    $user = User::whereCode($request->code)
        ->whereMobile($mobile)
        ->firstOrFail();

    $user->verification_code = 1;
    $user->save();

} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    return redirect()->back()->with('alert', 'error');
}

return redirect()->back()->with('success', 'ok');

否则,使用first代替firstOrFail,如果没有满足where条件的记录将返回null

$mobile = $request->session()->get('mobile');
$user = User::whereCode($request->code)
    ->whereMobile($mobile)
    ->first();

if(empty($user)){
    return redirect()->back()->with('alert', 'error');
} 

$user->verification_code = 1;
$user->save();
return redirect()->back()->with('success', 'ok');