簡體   English   中英

當記錄不存在時,SQL驗證的Laravel輸出

[英]Laravel output from SQL validation when record not exists

我正在學習Laravel ,但有一個我不明白的問題。

我正在使用查詢生成器來運行自己的查詢,並且我真的不知道當沒有記錄時如何返回錯誤消息:

public function store()
    {
       $item = request()->validate([
           'item' => 'required|min:6|max:10'
       ]);

         $details = DB::connection('sqlsrv')->table('TABLENAME')->where('ITEMID', '=',  $item )->get();

         return view('itemdetails.create', compact('details'));
    }

因此,如果$detailsnull我需要返回消息該怎么做? 類似於raw PHP

if(empty($details))
{
throw new Exception('My text')
}

或簽入blade文件:

 @if (count($details) != 1)

        I don't have a record!

    @endif

我嘗試了firstOrFail但似乎無法正常工作。

還有其他方法(最佳方法)嗎?

在控制器中

     $validator = \Validator::make($request->all(), [
               'item' => 'required|min:6|max:10'
            ]);             
     $details = DB::connection('sqlsrv')->table('TABLENAME')->where('ITEMID', '=',  $item )->get();
      if (!$details) {
           $validator->errors()->add('item', 'Item not found');
      }

       if ($validator->fails()) {
             return redirect()
                    ->back()
                    ->withErrors($validator)
                    ->withInput();
        }
    return view('itemdetails.create', compact('details'));
}

並在視圖文件中

{{$validator->errors()->first('item')}}

如果條件適合控制器,則只需使用正常

if($details) //True
{
   //Redirect to..
}else
{
   //Redirect to..  //False
}

對於刀片,您可以使用@if(count($details))如果為true,它將顯示信息@else {{No data}} @endif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM