2015-06-11 126 views
0

我正在創建書籍的CRUD,我想要做的就像生成的auth文件,如果有人註冊並且沒有在文本框中輸入任何內容,則會返回一條Flash消息。我現在正在做這件事,但我只能在成功創建一本書時發出一條閃光消息。這是我的存儲功能Laravel Flash消息驗證

public function store(Request $request) 
{ 
    $this->validate($request, [ 
     'isbn' => 'required|', 
     'title' => 'required', 
     'author' => 'required', 
     'publisher' => 'required' 
    ]); 
    Session::flash('msg', 'Book added!'); 
    $books = $request->all(); 
    Book::create($books); 
    return redirect('books'); 
} 

在我home.blade.php

@if(Session::has('msg')) 
<div class="alert alert-success"> 
{{ Session::get('msg') }} 
</div> 
@endif 

其實,這工作,但我想說明一些準備產生的錯誤閃光燈時,有人didnt完成字段。我怎樣才能做到這一點?

回答

1

你可以得到單個錯誤的領域

{!! $errors->first('isbn'); !!} 

,或者你可以得到所有的錯誤

@foreach ($errors->all() as $error) 
    <div>{{ $error }}</div> 
@endforeach 
+0

我該如何用控制器來實現? – FewFlyBy

+0

不明白你的意思是「用控制器實現」。我看到你已經驗證了你的控制器內的數據。以上代碼用於顯示錯誤。 – chanafdo

+0

我現在再次開始使用slimframework。我現在可以使用slim框架嗎,因爲現在我還沒有任何大項目?只是簡單的項目:) – FewFlyBy

1

您可以使用嘗試捕捉這樣

try{ 
$books = $request->all(); 
Book::create($books); 
Session::flash('msg', 'Book added!'); 
} 
catch(Exception $e){ 
Session::flash('msg', $e->getmessage()); 
} 
1

這是相當簡單,首先有一個很好的功能,就是redirect()->with()

所以,你的控制器代碼可能是:

public function store(Request $request) 
{ 
    $this->validate($request, [ 
     'isbn' => 'required|', 
     'title' => 'required', 
     'author' => 'required', 
     'publisher' => 'required' 
    ]); 
    if(Book::create($books)){ 
     $message = [ 
     'flashType' => 'success', 
     'flashMessage' => 'Book added!' 
     ]; 
    }else{ 
     $message = [ 
     'flashType' => 'danger', 
     'flashMessage' => 'Oh snap! something went wrong' 
     ]; 
    } 
    return redirect()->action('[email protected]')->with($message); 
} 

然後在您的視圖:

@if (Session::has('flashMessage')) 
    <div class="alert {{ Session::has('flashType') ? 'alert-'.session('flashType') : '' }}"> 
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> 
    {{ session('flashMessage') }} 
    </div> 
@endif 

獎金你可以把這個在您的頁腳,所以在3秒後警報框將消失:

<script> 
    $('div.alert').delay(3000).slideUp(300); 
</script> 
1

如果您使用的是Twitter Bootstrap,請嘗試使用Laracasts/Flash