Laravel 5.4 $error not showing/flashed - php

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.

Related

Missing required parameters for [Route: employees.update] laravel

i am creating crud in laravel.i ran into the problem with Missing required parameters for [Route: employees.update] [URI: employees/{employee}]. (View: C:\xampp\htdocs\jbs\resources\views\employees\edit.blade.php)what i tried so far i attach below. i added the model view controller below
Edit Blade Page
#extends('employees.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Employee</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('employees.index') }}"> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<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
<form action="{{ route('employees.update',$employees->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>StudentName:</strong>
<input type="text" name="name" value="{{ $employees->studname }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Course</strong>
<input type="text" name="name" value="{{ $employees->course }}" class="form-control" placeholder="course">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Fee</strong>
<input type="text" name="name" value="{{ $employees->fee }}" class="form-control" placeholder="fee">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
Controller
public function edit(Employee $employees)
{
return view('employees.edit',compact('employees'));
}
public function update(Request $request, Employee $employees)
{
$request->validate([
'studname' => 'required',
'course' => 'required',
'fee' => 'required',
]);
$employees->update($request->all());
return redirect()->route('employees.index')
->with('success','Employee updated successfully');
}
Model
protected $fillable = [
'studname', 'course','fee',
];
}
routes
Route::resource('employees','App\Http\Controllers\EmployeeController');
Your route parameter is employee not employees. Route parameter names for resource routes are singular by default. The route is actually like this:
employees/{employee}
So in your edit method of your Controller you are using the wrong parameter name so you are getting a new instance of Employee instead of the Implicit Route Model Binding that would inject the instance based on the route parameter, you need to match the typehinted parameter name to the route parameter name:
// {employee}
public function edit(Employee $employee)
{
...
return view(...., ['employee' => $employee]);
}
Now in the view you will have your actual existing Employee instance that you can use to generate the URL to the route instead of an empty Employee that does not have an id which was returning null:
{{ route('employees.update', ['employee' => $employee->id]) }}
// or
{{ route('employees.update', ['employee' => $employee]) }}
The route system can get the correct key from the model instance.
You should pass $employees->id as a hidden input field.
Make your route as
Route::post('employee/update', 'YourController#yourFunction');
and in the edit page the form action should look like
<form action="{{ route('employees.update'}}" method="POST">
make a hidden input field for passing id
<input type="hidden" name="id" value="{{$employees->id}}"></input>
You should pass the route name to the route function like this
route('route name',parameter1)
Example :
Route::post('employee/update/{id}' ,YourController#update)->name('update_employee');
<form action="{{ route('update_employee',$employees->id) }}" method="POST">
#csrf
...

After php artisan route:cache my routes stopped working because I have Closure based routes

I am working on a project on laravel, I have a few routes, I decided to php artisan route:cache and I got this error. My routes, almost of all them stopped working. When I click on a button for example, to update the user info, nothing happens anymore, how can I fix this or revert the changes I made with the routes cache, please help me
Macintoshs-MacBook-Air:dpmanager macintoshhd$ php artisan route:cache
Route cache cleared!
LogicException
Unable to prepare route [api/user] for serialization. Uses Closure.
at vendor/laravel/framework/src/Illuminate/Routing/Route.php:1081
1077| */
1078| public function prepareForSerialization()
1079| {
1080| if ($this->action['uses'] instanceof Closure) {
> 1081| throw new LogicException("Unable to prepare route [{$this->uri}] for serialization. Uses Closure.");
1082| }
1083|
1084| $this->compileRoute();
1085|
+15 vendor frames
16 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
I was searching for a solution, found this one, but I can't really implement it Unable to prepare route[api/user] for serialisation. Uses Closure - Laravel
Here is my routes code web.php
Route::get('/', 'HomeController#index');
Auth::routes();
Route::middleware('auth', 'isAdmin')->namespace('admin')->group(function(){
Route::get('users', 'UsersController#index') -> name('admin.users');
Route::get('admin/user/{id}', 'UsersController#getUser')->name('admin.user');
Route::post('admin/users/store', 'UsersController#store')->name('admin.user.store');
Route::put('admin/user/update', 'UsersController#update')-> name('admin.user.update');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Here is my api.php that I edited after I received the error
Route::middleware('auth:api')->get('users', 'UsersController#index');
Route::middleware('auth:api')->get('admin/user/{id}', 'UsersController#getUser');
Route::middleware('auth:api')->post('admin/users/store', 'UsersController#store');
Route::middleware('auth:api')->put('admin/user/update', 'UsersController#update');
Route::middleware('auth:api')->get('/home', 'HomeController#index');
Route::middleware('auth:api')->get('/home', 'HomeController#index');
EDITED
Here is the code for my two forms, my two blade templates
this is user.blade.php
#extends('admin.layouts.app')
#section('content')
<div class="row">
<div class="col-md-3 p-3 pl-5">
#component('admin.layouts.menus.sidebar')
#endcomponent
</div>
#if(session('success'))
<div class="alert-alert-success">
{{session('success')}}
</div>
#endif
<div class="col-sm-5 col-md-5 pl-2">
<div class="card">
<div class="card-header">
Информация за пациента
<span class="btn btn-sm float-right btn-primary" id="open-edit-details-modal">Редакция на информацията</span>
</div>
<div class="card-body">
<h5>Име: {{ $user -> name}}</h5>
<h5>Имейл: {{ $user -> email}}</h5>
<h5>Тип: {{ $user -> role}}</h5>
<h5>Активен: {{ $user -> isActive == 1 ? 'да' : 'не'}}</h5>
</div>
</div>
<div class="col-sm-4">
<div class="card">
</div>
</div>
</div>
</div>
{{-- /.row --}}
{{-- Modals --}}
<div id="edit-details-modal" class="modal-cont">
<div class="row">
<div class="col-sm-6 offset-sm-3" >
<div class="card mt-5">
<div class="card-header">Променете информацията за: {{ $user -> name }} <span class="float-right" id="close-edit-details-modal" style="cursor:pointer;"><b>X</b></span>
</div>
<div class="card-body">
{{-- Forms --}}
<form action="{{ route('admin.user.update') }}" method="POST">
#csrf
#method('PUT')
<input type="text" name="id" value="{{ $user -> id }}">
<div class="form-group">
<label for="name">Име на пациента</label>
<input type="text" class="form-control" name="name" value="{{$user -> name}}">
</div>
</form>
<div class="form-group">
<label for="email">Имейл на пациента</label>
<input type="text" class="form-control" name="name" value="{{$user -> email}}">
</div>
<div class="form-group">
<label for="role">Роля на пациента</label>
<select name="role" class="form-control">
<option value="{{$user -> role}}">{{$user -> role}}</option>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
<input type="text" class="form-control" name="name" value="{{$user -> role}}">
</div>
<div class="form-group">
<label for="isActive">Активност</label>
<select name="isActive" class="form-control">
{{--
#if ($user -> isActive == 1)
<option value="1">да</option>
<option value="0">не</option>
#else
<option value="0">не</option>
<option value="1">да</option>
#endif
--}}
<option value="1" {{$user->isActive == 1 ? 'default' : ''}}>да</option>
<option value="0" {{$user->isActive == 0 ? 'default' : '' }}> не</option>
</select>
</div>
<input type="submit" class="btn btn-primary btn" value="Промяна на информацията">
{{-- End of forms --}}
</div>
</div>
</div>
</div>
</div>
#endsection
#push('admin.layouts.scripts.scripts')
<script src="{{ asset('js/admin/user.js')}}"></script>
#endpush
#push('admin.layouts.styles')
<link rel="stylesheet" href="{{ asset('css/admin/user.css')}}" />
#endpush
and this is add_user.blade.php
<form action="{{route('admin.user.store')}}" method="POST" id="new-user-form" class="px-5 py-4">
#csrf
<div class="form-group">
<label for="name">Име на пациент:</label>
<input type="text" class="form-control {{$errors ->has('name') ? 'is-invalid' : ''}}" name="name">
#if($errors->has('name'))
<div class="invalid-feedback">
{{$errors -> first('name')}}
</div>
#endif
</div>
<div class="form-group">
<label for="email">Имейл на пациента</label>
<input type="text" class="form-control {{$errors ->has('email') ? 'is-invalid' : ''}}" name="email">
#if($errors->has('email'))
<div class="invalid-feedback">
{{$errors -> first('email')}}
</div>
#endif
</div>
<div class="form-group">
<label for="role" >Каква ще е неговата роля</label>
<select name="role" class="form-control {{$errors ->has('role') ? 'is-invalid' : ''}}">
<option value="user" default>Пациент</option>
<option value="admin">Фото студио</option>
</select>
</div>
</form>
<button class="btn btn-primary btn-block" id="show-new-user-form">Добави нов пациент</button>
Would you be able to show us the code used in your blade template so we can see the form parameters?
If you're using ajax to make an API call and you're trying to access the PUT route, then you need to pass a parameter into your request data object on the client side. For example, if I was using Axios I would run my query like this:
axios.post('/this/is/my/route', {
_method: 'PUT',
other: 'parameters',
go: 'here'
}).then(response => {
//Do something with the response
})
All requests made to the server are picked up as either GET or POST requests. The additional "_method: 'PUT'" parameter will tell laravel that it needs to access the PUT route.
If you're not making the request via ajax when submitting the form, then make sure that you have added the #method('PUT') in your form.
I fixed it, the problem was in the Validation
I checked for errors again, the problem was that on one of the Routes, the e-mail was actually not required, something like that, I fixed it in the below code, also, the name attribute for the html of the was name="name" instead of name="email", it could not run, did dd($request) too and checked it out, also about the other Route, where I am adding a user, the problem is that now somehow my button was actually not running the form, but was doing a javascript event on click, I added one more into the form itself, that a type="submit" and fixed it
public function update(Request $request){
$request -> validate([
'id' => 'required',
'name' => 'required',
'email' => 'required|unique:users,email',
'role'=>'required',
'isActive' => 'required',
]);
$user = User::find($request -> id);
$user -> name = $request -> name;
$user -> email = $request -> email;
$user -> role = $request -> role;
$user -> isActive = $request -> isActive;
$user -> save();
return redirect('admin/user/' . $user->id)-> with('success', 'Успешно променени детайли');
}
}

Laravel 5.7 MethodNotAllowedHttpException

I am getting an MethodNotAllowedHttpException error while im trying to update mine post. So I googled the error and found this laravel throwing MethodNotAllowedHttpException but it get explained that i need to make the route
an post request, where mine form actions go thruw but its already a post and it keeps throwing the same error and i cant figure out if the erros is in the form the web.php or the controller it self
edit.blade.php
<form method="POST" action="/posts/{{ $post->id }}/edit">
{{ csrf_field() }}
#method('PUT')
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title" name="title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="body">Body:</label>
<textarea id="body" name="body" class="form-control" rows="10">
{{
$post->body
}}
</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Edit</button>
</div>
#include('layouts.errors')
</form>
Web.php
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/{post}/edit', 'PostsController#edit');
Route::post('/posts/{post}/edit', 'PostsController#update');
Route::get('/posts/{post}/delete', 'PostsController#destroy');
PostsController.php
(this is the part that matters out of the controller if u want me to post the hole controller let me know)
public function edit(Post $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required'
]);
$post->update($request->all());
return redirect('/')->with('succes','Product updated succesfully');
}
You should try this:
View file:
<form method="POST" action="{{ route('post.update',[$post->id]) }}">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" id="title" name="title" value="{{ $post->title }}">
</div>
<div class="form-group">
<label for="body">Body:</label>
<textarea id="body" name="body" class="form-control" rows="10">
{{
$post->body
}}
</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Edit</button>
</div>
#include('layouts.errors')
</form>
Your Route
Route::post('/posts/{post}/edit', 'PostsController#update')->name('post.update');
You are submitting the form with the put method as defining #method('PUT') will make it a put route. Either define a route for put method like this Route::put('/posts/{post}/edit', 'PostsController#update'); or remove #method('PUT') from your blade file.
This problem 1 week took me but i solve it with routing
In edit.blade.php
{!! Form::open([route('post.update',[$post->id]),'method'=>'put']) !!}
<div class="form-group">
<label for="title">Title:</label>
{!! Form::text('title',$post->title,['class'=>'form-control',
'id'=>'title']) !!}
</div>
<div class="form-group">
<label for="body">Body:</label>
{!! Form::textarea('body', $post->body, ['id' => 'body', 'rows' => 10,
class => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Edit',['class'=>'btn btn-block bg-primary',
'name'=>'update-post']) !!}
</div>
{!! Form::close() !!}
#include('layouts.errors')
In Web.php
Route::resource('posts','PostsController');
Route::get('/posts/{post}/delete', 'PostsController#destroy');
Route::put('/posts/{post}/edit',['as'=>'post.update',
'uses'=>'PostController#update']);
Route::get('/', 'PostsController#index')->name('home');
Laravel will throw a MethodNotAllowedHttpException exception also if a form is placed by mistake this way inside a table:
<table><form><tr><td>...</td></tr></form><table>
instead of this :
<table><tr><td><form>...</form></td></tr></table>

Laravel redirect withErrors not working

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.

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.

Categories