Reputation: 13434
I am creating a CRUD of books and what I wanted to do is like the generated auth
files that if someone registers and didn't input any in the textbox, a flash message will return. I am doing that now in my crud but I can only make a flash message when a book is successfully created. This is my store function
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');
}
And in my home.blade.php
@if(Session::has('msg'))
<div class="alert alert-success">
{{ Session::get('msg') }}
</div>
@endif
This actually works but I want to show some ready generated error flash when someone didnt complete fields. How can I do that?
Upvotes: 0
Views: 3276
Reputation: 22852
It's pretty simple, first there's a sweet nice feature that is the redirect()->with()
So your controller code could be:
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('BooksController@index')->with($message);
}
Then on your view:
@if (Session::has('flashMessage'))
<div class="alert {{ Session::has('flashType') ? 'alert-'.session('flashType') : '' }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ session('flashMessage') }}
</div>
@endif
Bonus you can put this on your footer, so the alerts boxes will vanish after 3 seconds:
<script>
$('div.alert').delay(3000).slideUp(300);
</script>
Upvotes: 2
Reputation: 5443
you can use try catch like this
try{
$books = $request->all();
Book::create($books);
Session::flash('msg', 'Book added!');
}
catch(Exception $e){
Session::flash('msg', $e->getmessage());
}
Upvotes: 1
Reputation: 5124
You could get the individual errors for a field
{!! $errors->first('isbn'); !!}
or you can get all the errors
@foreach ($errors->all() as $error)
<div>{{ $error }}</div>
@endforeach
Upvotes: 1