2015-06-11 72 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