i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.
Related
I am trying to fetch details of some user based on id, if id does not exist in database, how to handle error in that case and how can i show some error message for assets/lang/en/somefile.php , saying that 'errorMessage' => 'Some error occured.Please try again!.',
$city=City::with('locations')->findOrFail($id);
// if $id does not exit how to handle error
// how to show message form asses/lang/en/somefile.php to user.
// like "please try again"
return view('admin.city.viewCity',compact('city'));
With laravel you can pass error to view like this,
controller,
Redirect::back()->withInput()->withErrors(['msg' => 'try again']);
view,
<ul class="errors">
#foreach ($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
You can just use find() instead of findOrFail(). Controller's method should looks like...
public function methodName(Request $request, $id)
{
$city = City::with('locations')->find($id);
if ($city === null) {
return redirect()->back()->withErrors(['msg' => 'Can not find city.']);
} else {
return view('admin.city.viewCity', [
'city' => $city,
]);
}
}
Or shorter version:
return $city === null
? redirect()->back()->withErrors(['msg' => 'Can not find city.'])
: view('admin.city.viewCity', [
'city' => $city,
]);
Please try this
$city = City::with('locations')->findOrFail($id);
if(count($city) > 0 ){
return view('admin.city.viewCity',compact('city'))
}else{
return view('your message inside balde')
}
or
$city = City::with('locations')->findOrFail($id);
if(count($city) > 0 ){
return view('admin.city.viewCity',compact('city'))
}else{
$errorMessage = "User not found";
return view('admin.city.viewCity',compact('errorMessage'))
}
Please try this what I have done before
if(!$city->isEmpty()){
return view('single', compact('city'));
}else{
return view('nodata', compact('city'));
}
noted: nodata it mean your blade view to show message error to user
So I am receiving data from a form that should reset user passwords:
Old Password: |field|
New Password: |field|
Confirm Password: |field|
And i want to be able to display a message out for the user if his old password does not match what he entered in the first field. I don't want to make an entirely new validation method and just want to throw an error to the use when i make my own if(). So how do I achieve this using the $errors variable that is available in my blade views
So here is an example of my controllers method
public function update(Request $request){
$this->validate($request,[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
$user = Auth::user();
if(password_verify($request->newPass,$user->password)){
$user = User::find($user->id);
$user->password = bcrypt($request->newPass);
$user->save();
}else{
//the code for adding a new key to $errors variable
return back(); Or return redirect('path');
}
}
So in the view I want to this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
You can do this in your controller:
$validator = Validator::make($request->all(),[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
And then before your return back();, add:
$validator->after(function($validator) {
$validator->errors()->add('tagName', 'Error message');
});
With your message.
I have a form that allows the user to upload 3 files.
Here is the Controller function called :
public function registerUpdate(CardAvsRequest $request){
$id = Auth::user()->id;
$first_name = User::find($id)->student->first_name;
$last_name = User::find($id)->student->last_name;
$name = $first_name . " " . $last_name;
$message = "";
if ($request->hasFile('carte-id'))
{
$image1 = $request->file('carte-id');
if($image1->isValid())
{
if ($request->hasFile('avs'))
{
$image2 = $request->file('avs');
if($image2->isValid())
{
if ($request->hasFile('permit'))
{
$image3 = $request->file('permit');
if($image3->isValid())
{
$path = config('card.path')."/$id";
$name = "carte-id.".$image1->getClientOriginalExtension();
$image1->move($path, $name);
$path = config('card.path')."/$id";
$name = "avs.".$image2->getClientOriginalExtension();
$image2->move($path, $name);
$path = config('card.path')."/$id";
$name = "permit.".$image3->getClientOriginalExtension();
$image3->move($path, $name);
$message = "Super ! Vous avez importé tous les fichiers nécessaires.";
//ici on dit dans la DB que l'utilisateur à uploadé tous les fichiers
}
}
}
}
}
}
return redirect()->route('account', $id)->with('message', $message);
}
So the Validation rules are set in CardAvsRequest.php :
class CardAvsRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'carte-id' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'avs' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
'permit' => 'mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000',
];
}
}
I would like to know how to display errors if a file isn't validated.
Isn't it supposed to work like this ?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Any ideas ?
This is how Laravel 5.2 documentation suggestion to validate input and return error if any. The view looking good and will display error if occurred.
public function store(Request $request)
{
$rule = 'required|file|mimes:jpg,png,pdf,gif,jpeg,tiff,doc,docx,odt|max:10000';
$validator = Validator::make($request->all(), [
'file_one' => $rule,
'file_two' => $rule,
'file_three' => $rule,
]);
if ($validator->fails()) {
return redirect('account')
->withErrors($validator)
->withInput();
}
// no errors proceed managing your files
}
Yes but in that case you have to remember that you have to put that code:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
In form file.
Hi Im using a repository pattern in laravel and to create tasks and they all have an estimated time and the project has a capacity of hours. So i need to pass this back when the task is created so they can see how many hours are left.
I have this so far:
TaskRepository.php
public function createTask(array $attributes)
{
if ($this->validator->createATask($attributes)) {
$newAttributes = [
'project_id' => $attributes['project_id'],
'estimated_time' => $attributes['estimated_time'],
'task_name' => $attributes['task_name']
];
$task = Task::updateOrCreate([
'task_name' => $attributes['task_name']
],
$newAttributes);
$task->save();
$project = Project::find($attributes["project_id"])->pluck('capacity_hours');
$tasks = Task::find($attributes["project_id"])->lists('estimated_time');
$tasksTotal = array_sum($tasks);
$capcity_left = ($project - $tasksTotal);
return $capcity_left;
}
throw new ValidationException('Could not create Task', $this->validator->getErrors());
}
and in my controller I have this:
TaskController.php
public function store() {
try {
$this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
if (Request::ajax()) {
return Response::json(['errors' => $e->getErrors()], 422);
} else {
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
if (Request::ajax()) {
return Response::json(["message" => "Task added",'capcity_left'=> $capcity_left]);
} else {
return Redirect::back()->with('success', true)->with(['message', 'Task added', 'capcity_left'=>$capcity_left ]);
}
}
and I have a partial for errrors:
#if(Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span></button>
<strong>{{ Session::get('message', '') }} Capacity Left:{{ Session::get('capcity_left', '') }}</strong>
</div>
#endif
However I get this error:
Undefined variable: capcity_left
Any ideas how I can pass this back to the controller? I thought I was by saying return $capcity_left; Do I need to catch this in the controller? If so how can I do that?
You forgot to assign the return value of the createTask method when calling it from the controller. So you need to do this:
public function store() {
try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
// ...
}
I am trying to make a authentication system and the only issue that I am having is that it will not display the errors if the wrong creds are used. It shows the error when one of the fields is empty but not when they are both filled with wrong info. Can someone help me figure out what is wrong? Thanks for all the help!
Here is my view
{{ Form::open([
"route"=>"user/login",
"autocomplete"=>"off"
]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), [
"placeholder"=>"Username"
]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", [
"placeholder"=>"Password"
]) }}
#if($error = $errors->first("password"))
<div class="error">
{{ $error }}
</div>
#endif
{{ Form::submit("Login") }}
{{ Form::close() }}
here is the controller
<?php
use Illuminate\Support\MessageBag;
class UserController extends BaseController
{
public function loginAction()
{
$errors = new MessageBag();
if($old = Input::old("errors")) {
$errors = $old;
}
$data = [
"errors"=>$errors
];
if(Input::server("REQUEST_METHOD") == "POST") {
$validator = Validator::make(Input::all(), [
"username"=>"required",
"password"=>"required"
]);
if($validator->passes()) {
$credentials = [
"username"=>Input::get("username"),
"password"=>Input::get("password")
];
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
} else {
echo "Login failed";
$data["errors"] = new MessageBag([
"password"=>[
"Username and/or password invalid."
]
]);
$data["username"] = Input::get("username");
return Redirect::route("user/login")
->withInput($data);
}
}
return View::make("user/login", $data);
}
}
It looks like you are not displaying any message if the authentication fails. Auth::attempt() will try to match the username and password and if it fails it should add something to the errors array.
if(Auth::attempt($credentials)) {
//return Redirect::route("user/login");
echo "login success";
}
else // add this
{
echo 'login failed - username and/or password provided are not correct';
}
That said, you probably need to add an else statement here.