Using the redirect method, errors are not sent to view - laravel

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

Related

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>

Validator in Laravel 5.6 not delivering $error messages

I am coding in Laravel 5.6 and i have a layout file called errors.blade with the contents of:
#if(session('status'))
<div class="alert alert-dismissible alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ session('status') }}
</div>
#endif
#if(count($errors))
<div class="alert alert-dismissible alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
#foreach($errors as $error)
<ul>
<li>{{ $error }}</li>
</ul>
#endforeach
</div>
#endif
And my controller that insterts data into db and uses the $this->validate is:
public function store()
{
$this->validate(request(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'username' => 'required',
'password' => 'required|confirmed',
'discord' => 'required'
]);
Admin::create([
'first_name' => request('first_name'),
'last_name' => request('last_name'),
'email' => request('email'),
'username' => request('username'),
'password' => bcrypt(request('password')),
'discord' => request('discord'),
]);
return redirect('/admin/login')->with('status', 'Install successfully completed. Use the form below to login to your account.');
}
As you can see i am sending back a session with the name of status which i have setup to show in my errors file, which works perfectly. But as soon as i leave a field blank or mismatch the passwords on purpose i get this from the actual $errors:
This is happening on all pages. I don't know what exactly is the problem. The status messages work, but the error message here doesn't work. It happens with any error with validator or even with the:
return redirect()->route('admin-login')->withErrors('Incorrect
Username or Password.');
Just a little more info, i am using a guard for admin and guard for the default laravel web to separate sessions of admin and regular users. I don't know if this could be any of the cause. Any help is greatly appreciated to remove this road block for me and any other users who have ran or may run into this.
Change the #foreach to this:
#foreach($errors->all() as $error)

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 flash message validation

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

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