Laravel flash message validation - laravel

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?

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>

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

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());
}

Related

Using the redirect method, errors are not sent to view

When I use return view('login')->withErrors($validator->errors());, I get the errors returned if any. Now, if I use the Redirect method/class, it doesn't return the data.
I need to use redirect. I tested it in several ways, going through the different errors, but nothing works. I've read documentation, blogs and everything I do doesn't work.
I already tried return Redirect::back()->withErrors(['msg' => 'The Message']); and in the blade `{{ session()->get('msg') }}, but nothing .
I need some help as I have tried many things and nothing works.
Controller:
public function checkUserExists(Request $request)
{
$email = $request->input('email');
$validator = Validator::make(
$request->all(),
[
'email' => ['required', 'max:255', 'string', 'email'],
'g-recaptcha-response' => ['required', new RecaptchaRule],
],
$this->messages
);
if ($validator->fails()) {
// return view('login')->withErrors($validator->errors());
// return Redirect::back()->withErrors(['msg' => 'The Message']);
return Redirect::route('login')->withErrors($validator->errors());
// return Redirect::route('login')->withErrors($validator);
// return redirect()->back()->withErrors($validator->errors());
// return Redirect::back()->withErrors($validator)->withInput();
}
...
}
At the moment my bucket is just with this:
{{-- Errors --}}
#if ($errors->any())
<div class="alert alert-danger" role="alert">
<ul>
#foreach ($errors->all() as $key => $error)
<li>
{{ $error }}
</li>
#endforeach
</ul>
</div>
#endif
Version of Laravel: "laravel/framework": "^7.29",
try this code to pass the errors back to the view:
public function checkUserExists(Request $request)
{
$email = $request->input('email');
$validator = Validator::make(
$request->all(),
[
'email' => ['required', 'max:255', 'string', 'email'],
'g-recaptcha-response' => ['required', new RecaptchaRule],
],
$this->messages
);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
...
}
& in your view, you can access the errors using with:
{{-- Errors --}}
#if ($errors->any())
<div class="alert alert-danger" role="alert">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
this should work if your view is correct
and you are using the correct path to your view
in your redirect()->back() method

How to break line in textarea in laravel and then echo it by foreach loop?

The name of my controller is ProductController, This is my controller
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'product_detail' => 'required',
'product_image' => 'required',
'admin_name' => 'required',
]);
$product_image = $request->file('product_image');
$new_name = rand().'.'.$product_image->getClientOriginalExtension();
$product_image->move(public_path('product_image'), $new_name);
$form_data = array(
'product_image' => $new_name,
);
// Product::create($form_data);
$product = Product::create([
'product_name' => $request->input('product_name'),
'product_detail' => $request->input('product_detail'),
'admin_name' => $request->input('admin_name'),
'product_image' => $new_name,
]);
return redirect('products')->with('success', 'Data Added successfully.');
}
This is my index page where I want to echo it, I have doubt in Product_detail
#foreach($products as $product)
<div class="col-lg-4 col-md-6 portfolio-item filter-Interior">
<div class="portfolio-wrap">
<div class="portfolio-info">
<h4>{{$product->product_name}}</h4>
<p>
<ul style="color: white">
<li>{{$product->product_detail}}</li>
</ul>
</p>
You can use php's inbuilt function nl2br() or you can explode by PHP_EOL and then run the for loop for unordered list.
<p>{!! nl2br($body) !!}<p>
<!-- OR -->
<ul>
#foreach (explode(PHP_EOL, $body) as $item)
<li>{{ $item }}</li>
#endforeach
</ul>

Laravel & Ajax send HTML form with errors

Here is an action:
public function postMessageAjax(Request $request)
{
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
return view('Guestbook.postMessage');
}
And here is the view:
{!! BootForm::open(['id' => 'messageForm']) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img('flat') !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
The problem is that Laravel somehow determines that that is an Ajax request and set an JSON of errors (if they're present) to Response instead of retrieving HTML code of form plus errors messages for each input individually. The question is: how do I force it to render the view with errors like if it weren't through Ajax?
UPDATE: this is what I want to get (the form itself and errors if they're present):
For #OuailB:
I've just noticed that when I do a normal POST request, it redirects me to the same page through a GET request so it seems like the error messages actually appear in the GET's body, not POST's so maybe there is no way. I'll think about it, thanks for your help!
You can create validator manually, and if it fails return what you want:
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput($request->all());
}
Try this code:
public function postMessageAjax(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return view('Guestbook.postMessage')
->withErrors($validator);
}
// Store your message here
}
Edit :
For displaying the errors, you can add this code into your view :
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel 5.2 - not show errors

It's impossible to show errors in views
here is my Controller:
public function create(){
return view('articles.create');
}
public function store(Request $request){
$this->validate($request, [
'title' => 'required|max:5',
'content' => 'required',
]);
}
this is my view create.blade.php:
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops!</strong> Something went wrong!.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Kernel.php
ShareErrorsFromSession already there
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
here is the route.php
i have added the route in web
Route::group(['middleware' => ['web']], function () {
Route::get('articles/create', 'ArticlesController#create'); // Display a form to create an article...
});
Route::get('articles', 'ArticlesController#index'); // Display all articles...
Route::post('articles', 'ArticlesController#store'); // Store a new article...
Route::get('articles/{id}', 'ArticlesController#show');
You can try something like this.
$data = array();
$messages=array(
'required' => "You can't leave this empty",
);
$datavalidate = array(
'name' => $request->name,
);
$rules = array(
'name' => 'required',
);
$validator = Validator::make($datavalidate,$rules,$messages);
if($validator->fails()){
return Redirect::back()->withErrors($validator);
}
And now print it on the view file.
{!! dd($errors) !!}

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources