Laravel redirect withErrors not working - php

SO i've trying to make simple laravel validation, but kinda stuck because i cannot return validation error message.
Controller:
//for "GET" method
public function courseAdminCreate()
{
return view('course/adminCreate');
}
//for "POST" method
public function doCourseAdminCreate()
{
$rules = array(
'name' => 'required',
'contact_name' => 'required',
'contact_number' => 'required|numeric',
'account_number' => 'required|numeric',
'address' => 'required',
'latitude' => 'required',
'longitude' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
//get error message
$messages = $validator->messages();
//die($messages); //if i using DIE command, error message appear
return redirect("course/admin/create")->withErrors($validator);
} else {
//Save to DB
}
}
Routes.php:
//other code
Route::get('course/admin/create', ['as' => 'courseAdminCreate', 'uses' => 'CourseController#courseAdminCreate']);
Route::post('course/admin/create', ['as' => 'doCourseAdminCreate', 'uses' => 'CourseController#doCourseAdminCreate']);
//other code
Views:
#extends('layouts.app')
#section('title')
Course
#stop
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
#yield('title') Add
</div>
<div class="panel-body">
{!! Form::open(['url' => '/course/admin/create']) !!}
<div class="row">
<div class="col-lg-12">
<!--START PRINT ERROR MESSAGE -->
#if (count($errors) > 0)
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</div>
#endif
<!-- END PRINT ERROR MESSAGE -->
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Course Name</label>
<input class="form-control" name="name" placeholder="name.." required>
</div>
<div class="form-group">
<label>Contact Name</label>
<input class="form-control" name="contact_name" placeholder="contact.." required>
</div>
<div class="form-group">
<label>Contact Number</label>
<input class="form-control" name="contact_number" placeholder="number.." required>
</div>
<div class="form-group">
<label>Account Number</label>
<input class="form-control" name="account_number" placeholder="account.." required>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Address</label>
<textarea class="form-control" name="address" rows="5" placeholder="address.." required></textarea>
</div>
<div class="form-group">
<label>latitude</label>
<input class="form-control" name="latitude" placeholder="latitude.." required>
</div>
<div class="form-group">
<label>longitude</label>
<input class="form-control" name="longitude" placeholder="longitude.." required>
</div>
</div>
<!-- /.col-lg-12 -->
<div class="col-lg-12">
<input type="submit" class="btn btn-default btn-success" value="Save"/>
Cancel
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row (nested) -->
{!! Form::close() !!}
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
#stop
The validation is actually working, so for instance if i input other character beside numeric in "contact_number" it will redirect me back to course/admin/create, the problem are i cannot print the message. $errors in the view always count as empty array if i try to var_dump it.
Hope my information is enough, thank you very much.

The problem is probably in your controller. You can use the $this->validate() method in your Controller method instead of the facade method Validator::make. As you are not using any manually created validators/rules there is no point in using the make method.
If there is any error while validation, Laravel will automatically redirect back to the page the user is coming from - so you do not need any custom redirect logic.
Try this in your controller. You can inject the complete request into your doCourseAdminCreate method and pass it to the $this->validate() method.
//for "GET" method
public function courseAdminCreate()
{
return view('course/adminCreate');
}
//for "POST" method
public function doCourseAdminCreate(Request $request)
{
$rules = array(
'name' => 'required',
'contact_name' => 'required',
'contact_number' => 'required|numeric',
'account_number' => 'required|numeric',
'address' => 'required',
'latitude' => 'required',
'longitude' => 'required'
);
$this->validate($request, $rules);
// Save to db
}
All error messages are autommatically stored into the $errorvariable, that you are already using in your template.

Related

My Laravel Website is redirecting all post request to index page

Having Problem with POST Request
All the get routes are working fine.
Post route when submiting any form it gets updated in DB and then redirected to homepage but where I go back to previous link. I see that I am having all the success and errors on that page before getting redirected to homepage.
My POST Route:
Route::post('/update-faq', 'FaqController#update')->name('admin.faq.update');
My Controller Function:
public function index(){
$all_faqs = Faq::all();
return view('backend.pages.faqs')->with(['all_faqs' => $all_faqs]);
}
public function update(Request $request){
$this->validate($request,[
'title' => 'required|string',
'description' => 'required|string',
'status' => 'nullable|string|max:191',
]);
Faq::find($request->id)->update([
'title' => $request->title,
'description' => $request->description,
'status' => $request->status,
'is_open' => !empty($request->is_open) ? 'on' : '',
]);
return redirect()->back()->with(['msg' => 'Faq Updated...','type' => 'success']);
}
My View:
<div class="modal fade" id="faq_item_edit_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ 'Edit Faq Item' }}</h5>
<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
</div>
<form action="{{ route('admin.faq.update') }}" id="faq_edit_modal_form" enctype="multipart/form-data"
method="post">
<div class="modal-body">
#csrf
<input type="hidden" name="id" id="faq_id" value="">
<div class="form-group">
<label for="edit_title">{{ 'Title' }}</label>
<input type="text" class="form-control" id="edit_title" name="title"
placeholder="{{ 'Title' }}">
</div>
<div class="form-group">
<label for="edit_is_open">{{ 'Is Open' }}</label>
<label class="switch">
<input type="checkbox" name="is_open" id="edit_is_open">
<span class="slider"></span>
</label>
</div>
<div class="form-group">
<label for="edit_description">{{ 'Description' }}</label>
<textarea name="description" id="edit_description" cols="30" rows="10"
class="form-control max-height-150" placeholder="{{ 'Description' }}"></textarea>
</div>
<div class="form-group">
<label for="edit_status">{{ 'Status' }}</label>
<select name="status" id="edit_status" class="form-control">
<option value="publish">{{ 'Publish' }}</option>
<option value="draft">{{ 'Draft' }}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">{{ 'Close' }}</button>
<button type="submit" class="btn btn-primary">{{ 'Save Changes' }}</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(document).on('click', '.faq_edit_btn', function() {
var el = $(this);
var id = el.data('id');
var title = el.data('title');
var form = $('#faq_edit_modal_form');
form.find('#faq_id').val(id);
form.find('#edit_title').val(title);
form.find('#edit_description').val(el.data('description'));
form.find('#edit_status option[value="' + el.data('status') + '"]').attr('selected', true);
if (el.data('is_open') != '') {
form.find('#edit_is_open').attr('checked', true);
} else {
form.find('#edit_is_open').attr('checked', false);
}
});
});
</script>

PHP laravel object not creating in 5.8

I have a PHP Laravel CRUD application I made where I am using MVC style. I have controllers views and models. My database migration is made and my table in the database is made with php artisan migrate. I am using php 7.3 and laravel 5.8.
On my create view I go to create a single object in my database and my errors are thrown saying nothing in text box (no input) If I comment out the errors then just I click my submit button and nothing happens nothing is entered into my db. I have looked at many different crud examples and I am not sure why my object isn’t being created. Here is what I have
My env is setup correctly I just don’t get the not creating object.
//view create
#section('main')
<section id="section-content" class="text-center">
<div class="container contentdiv rounded">
<div class="row">
<div class="col-md-12">
<div class="pb-2 mt-4 mb-2 border-bottom clearfix">
<h2>Create Contact</h2>
</div>
<div >
<a class="btn btn-success" href="{{route('contacts.index')}}">Back</a>
</div>
</div>
<!-- <div class="col-md-10 mx-auto">
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div><br />
#endif
</div> -->
<div class="row">
<div class="col-md-10 mx-auto mt-3">
<form method="POST" action="{{ route('contacts.store') }}">
#csrf
<div class="form-group row">
<label for="txtfn" class="col-sm-3"><b>First Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
</div>
</div>
<div class="form-group row">
<label for="txtln" class="col-sm-3"><b>Last Name:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtln" id="txtln"/>
</div>
</div>
<div class="form-group row">
<label for="txtem" class="col-sm-3"><b>Email:</b></label>
<div class="col-sm-9">
<input type="text" class="form-control" name="txtem" id="txtem"/>
</div>
</div>
<button type="submit" class="btn btn-primary">Create Contact</button>
</form>
</div>
</div>
</div>
</section>
//controller
namespace App\Http\Controllers;
use App\Contact;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function store(Request $request)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required'
]);
$contact = new Contact([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
'email' => $request->get('email'),
'job_title' => $request->get('job_title'),
'city' => $request->get('city'),
'country' => $request->get('country')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact saved!');
}
public function index()
{
$contacts = Contact::all();
return view('contacts.index', compact('contacts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('contacts.create');
}
// model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title'
];
}
Your problem is that your input names do not correspond to the keys you are referencing in your store() method:
for example:
<input type="text" class="form-control" name="txtfn" id="txtfn"/>
here, your input name is txtfn, but in your store method, you are looking for first_name.
'first_name' => $request->get('first_name')
so, $request->get('first_name') returns null as if you didn't pass any value.
You must make your input names match with the keys you are using in your store method, either by changing input names, or by changing key names.
example:
<input type="text" class="form-control" name="first_name" />
<input type="text" class="form-control" name="last_name" />
<input type="text" class="form-control" name="email" />

Laravel 5.4 $error not showing/flashed

I have a fresh installation of Laravel 5.4 using vagrant for windows.
Now as I followed through the tuts in laracast and tried the form validation it was all fine but the $errors variable just doesn't contain any error messages at all.
snippet is from PostsController
public function store()
{
$this->validate(request(), [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
Post::firstOrCreate(request(['title', 'body']));
return redirect()->route('create-post');
}
snippet from my create.blade.php
#extends('layout')
#section('content')
<main role="main" class="container">
<div class="row">
<div class="col-md-8 blog-main">
<h3 class="pb-3 mb-4 font-italic border-bottom">
Create Post Form
</h3>
<form action="/api/posts" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="Title" name="title" value="">
<small class="text-danger">{{ $errors->first('title') }}</small>
</div>
<div class="form-group">
<label for="body">Content</label>
<textarea class="form-control" id="body" rows="5" name="body" placeholder="Contents Here.." value=""></textarea>
<small class="text-danger">{{ $errors->first('body') }}</small>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
<div class="form-group">
<div class="alert alert-{{ $errors->any() ? 'danger' : 'default' }}">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
</form>
</div>
#include('partials.sidebar')
</div>
</main>
#endsection
and the result after validation failed
Is there something that I am missing or somethings wrong?
Edit
here's the snippet of my route:
Route::get('/', 'PostsController#index');
Route::get('/posts/{post}', 'PostsController#show');
Route::get('/create', function() {
return view('posts.create');
})->name('create-post');
Route::post('/posts', 'PostsController#store');
Found the answer.
Since that it's 5.4 I didnt notice that all the web.php was under a middleware called web
that that includes with it the \Illuminate\View\Middleware\ShareErrorsFromSession::class
my api/posts was on the api middleware thats why there's no session shared whatsoever.
also this link helped solved this.
Laravel 5.2 $errors not appearing in Blade
You are passing Request object in the validator. You need to change the validation code a bit:
$this->validate(request()->all(), [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
Read more in the docs.
You can validate this way
$this->validate($request, [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
I hope this will work.

Laravel 5.2 Validation Error not appearing in blade

I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.
Here is the controller:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}
Here is the route:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('index');
})->name('main');
Route::post('/saveUser',[
'uses' => 'AppController#saveUser',
'as'=>'saveUser',
]);
});
Here is the blade view page:
#extends('layouts.master')
#section('title')
Create User
#endsection
#section('content')
#include('partials.message-block')
<div class="container" >
<h3> Student Register </h3>
{!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST')) !!}
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required placeholder="Name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required placeholder="email">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" name="phone" class="form-control" required placeholder="phone">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="course_id" >
#foreach($input as $row)
<option value="{{$row->id}}">{{$row->name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
#endsection
And here is the error-message block:
#if(count($errors) > 0)
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
#if(Session::has('message'))
<div class="row">
<div class="col-md-4 col-md--offset-4 success">
{{Session::get('message')}}
</div>
</div>
#endif
Try to remove web middleware if you're using 5.2.27 or higher. The thing is now Laravel automatically applies web middleware to all routes inside routes.php and if you're trying to add it manually you can get errors.
app/Providers/RouteServiceProvider.php of the 5.2.27 version now adds web middleware to all routes inside routes.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Use Below line in your controller
use Validator;
Add below code in your controller function where your request is sent.
$validator = Validator::make($request->all(), [
'fname' => 'required|max:20|min:4',
'uemail' => 'required|email',
'message' => 'required',
]);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withErrors($messages)->withInput($request->all());
}
In your view page
#if ($errors->any())
<label for="fname" class="error">{{ $errors->first('fname') }}</label>
#endif
For display individual field wise error.
if you are using laravel 5.2+ then please use the below code.
Moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php
Alexey is correct and if you're not comfortable with that then you can just add this code into your view for the session messages to show.
#if(Session::has('message'))
<div class="alert alert-success">{{Session::get('message')}}</div>
#endif
#if(count($errors)>0)
<ul>
#foreach($errors->all() as $error)
<li class="alert alert-danger">{{$error}}</li>
#endforeach
</ul>
#endif
I've done this in laravel 5.5. Please do confirm if this helps you out.

Validation error message not showing and datas not being saved to database

I am trying to first validate the inputs and then add the values to database but neither I am able to see the validation error message nor I am able to insert records to database. I have a table in database named 'news' where I have
this is my boxed.blade.php
<form class="form-horizontal" role="form" method="post" action="/addNews" novalidate>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Title</label>
<div class="col-lg-10">
<input type="text" name="title" class="form-control" id="inputEmail1" placeholder="News Title" value="{{ Input::old('title') }}">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 col-sm-2 control-label">Description</label>
<div class="col-lg-10">
<textarea name="description" class="form-control" rows="6">{{ Input::old('description') }}</textarea>
</div>
</div>
<div class="form-group">
<label for="inputEmail1" class="col-lg-2 col-sm-2 control-label">Reporter</label>
<div class="col-lg-10">
<input type="text" name="reported_by" class="form-control" id="inputEmail1" placeholder="Reporter Name" value="{{ Input::old('reported_by') }}">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-danger"><i class="fa fa-comments"></i> Add To List</button>
</div>
</div>
</form>
And routes.php
Route::get('addNews', function()
{
return View::make('pages.boxed');
}
);
Route::post('addNews', function()
{
//processing the form
$rules = array(
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()){
$message = $validator->message();
return Redirect::to('addNews')->withErrors($validator)->withInput(Input::all());
}
else{
$news = new News;
$news->title = Input::get('title');
$news->description = Input::get('description');
$news->reported_by = Input::get('reported_by');
$news->status = Input::get('status');
$news->save();
return Redirect::to('addNews');
}
}
This is my model News.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $fillable = array('title', 'description', 'reported_by', 'status');
}
If you want to see the error, place the following code above your form:
#if (count($errors) > 0)
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
UPDATE 1: Instead of defining the methods in routes.php file, define it in a Controller called NewsController
So, to do this, update your routes.php file to this:
Route::get('/addNews', 'getNewsForm');
Route::post('/addNews', 'postNewsForm');
NewsController.php
/**
* Display the add news form to the user.
*
* #return view
*/
public function getNewsForm()
{
return View::make('pages.boxed');
}
/**
* Store the input in the database after validation
*
* #param $request Illuminate\Http\Facade\Request
*/
public function postNewsForm(Request $request)
{
$this->validate($request, [
'title' => 'required',
'description' => 'required|min:50',
'reported_by' => 'required'
]);
News::create($request->all());
return redirect('/addNews');
}

Categories