I have a user resource with is linked in the users table.
My Route:
Route::resource('user', 'UserController');
UserController.php
public function edit($id)
{
$user = User::find($id);
return view('user.edit')->with(array('user'=>$user));
}
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
}
And my View
{!! Form::model($user, array('route' => array('user.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) !!}
#if (count($errors) > 0)
<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
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
#endif
#endforeach
</div>
<div class="form-group"><label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10"><input type="text" name="name" id="name" value="{{$user->name}}" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">ID Number</label>
<div class="col-sm-10"><input type="text" name="id_number" id="id_number" value="{{$user->id_number}}" class="form-control"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Save changes</button>
</div>
</div>
{!! Form::close() !!}
So with this setup I expect that when click the submit button on my page it will go in the update() function just like my other resource. But problem is when I click submit it will direct me to
http://localhost/hrs/public/user/1
and a white blank page with no errors what so ever. So it means it's going to my update function? I am following same pattern with my other resource and this is the only one not working.
You have wrong web server configuration. You should point your web server (usually Apache or nginx) to a public directory of your Laravel project. After that restart web server.
For example for Apache correct configuration will be something like this:
DocumentRoot "C:/xampp/htdocs/hrs/public"
<Directory "C:/xampp/htdocs/hrs/public">
Found the problem, I don't have the else part of the validation. as that is where the event goes to. Since I don't have it, it will do nothing.
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
else
{
dd($rules);
}
Related
I am struggling to update data in the database with an edit form and couldn't find anything online that fits the logic of my setup.
I have a add button, delete button and an edit button. Adding and Deleting works but Editing does not update the data.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
View:
#extends('layouts.app')
#section('content')
<div class="container flex-center">
<div class="row col-md-8 flex-column">
<h1>Edit a link</h1>
#foreach ($links as $link)
<form action="{{ url('link/'.$link->id) }}" method="POST">
{!! csrf_field() !!}
#method('PUT')
#if ($errors->any())
<div class="alert alert-danger" role="alert">
Please fix the following errors
</div>
#endif
<h3 class="edit-link-title">{{ $link->title }}</h3>
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $link->title }}">
#if($errors->has('title'))
<span class="help-block">{{ $errors->first('title') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('url') ? ' has-error' : '' }}">
<label for="url">Url</label>
<input type="text" class="form-control" id="url" name="url" placeholder="URL" value="{{ $link->url }}">
#if($errors->has('url'))
<span class="help-block">{{ $errors->first('url') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="description">{{ $link->description }}</textarea>
#if($errors->has('description'))
<span class="help-block">{{ $errors->first('description') }}</span>
#endif
#endforeach
</div>
<button type="submit" class="btn btn-default submit-btn">Submit</button>
</form>
</div>
</div>
#endsection
web/route controller:
use Illuminate\Http\Request;
Route::post('/submit', function (Request $request) {
$data = $request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link = tap(new App\Link($data))->save();
return redirect('/');
});
use App\Link;
Route::delete('/link/{link}', function (Link $link) {
// Link::destroy($link);
$link->delete();
return redirect('/');
});
Route::PUT('/link/{link}', function (Link $link) {
$link->update();
return redirect('/');
});
As a design pattern, it's often recommended to separate your controller from the routes. The reason your edit is not updating is that you're not providing the model with the data from the request:-
Route::PUT('/link/{link}', function (Request $request, Link $link) {
$request->validate([
'title' => 'required|max:255',
'url' => 'required|url|max:255',
'description' => 'required|max:255',
]);
$link->update($request->all());
return redirect('/');
});
In a controller, you could abstract away the validation logic to a validation helper function to avoid duplicating code.
Good luck!
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.
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.
I am using Laravel 5 and I want to use input validation for my form. But my validation is not working. Do you know why? Here is the view:
<div class="form-group"><br>
<label for="jenis_surat" class="control-label col-sm-2">Jenis Surat</label>
<div class="col-sm-7">
<script type="text/javascript">
#if($errors->any())
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
</script>
<input class="form-control" type="text" name="jenis_surat" id="jenis_surat">
</div>
<div class="col-md-1">
<input class="form-control" type="hidden" name="_token" value="{{ Session::token() }}">
<a class="btn btn-success" data-toggle="modal" data-target="#konfirmasi_submit_jenis_surat">Submit</a>
</div>
</div>
and this is the controller:
public function tambahjenissurat(Request $request)
{
//input validation
$this->validate($request, [
'jenis_surat' => 'required'
]);
$jenis_surat = $request['jenis_surat'];
$jenissurat = new JenisSurat();
$jenissurat->jenis_surat = $jenis_surat;
$jenissurat->save();
return redirect()->route('jenissurat');
}
Could you please try like this?
1. Import the validator using use Validator;
2. Change the code that validates the rule as given below
$rules = array(
'jenis_surat' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator);
}
I am having some issues with the redirect when the form validation fails.
The code that I am using is the following:
// -> use Illuminate\Support\Facades\Validator;
public function subscribe(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|unique:subscriber|email',
]);
if ($validator->fails()) {
return redirect('main')
->withErrors($validator)
->withInput();
}
$email = $request->input('email');
$randomId = $this->generateRandomUserId();
$subscriberSource = $request->input('utm_source');
// ... Save user
}
And this is my form:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email"
value="{{ $email or old('email') }}">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-refresh"></i>Subscribe now
</button>
</div>
</div>
</form>
The users should put their email in the email field and then get validated by the above piece of code. The issue is that the user is never redirected back to the main page
You can use:
$this->validate($request, [
'email' => 'required|unique:subscriber|email',
]);
Instead of creating a new validator istance, so Laravel will automatically redirect back with all errors and all inputs to the previous page if validation fails.