Laravel Message Bag Error - php

Am working on form validations for newsletter for a project am on, the news letter form appears on every page so it will also appear on the longin and registration page so i decided to make use of Laravel Message Bags to store the news letter errors but it keeps giving me an undefined property error on the actual page i check and output echo the errors, i don't know if am doing something wrong here are the details though!
The Error:
Undefined property: Illuminate\Support\MessageBag::$newsletter
My code In the Controller:
return Redirect::back()->withInput()->withErrors($inputs, "newsletter");
My code in the View:
#if($errors->newsletter->any())
<p>
{{$errors->newsletter->any()}}
</p>

Code in controller:
$post_data = Input::all();
$validator = Validator::make(Input::all(),
array(
'email' => 'required',
'password' => 'required'
));
if ($validator->fails()) {
return Redirect::back()
->withInput()
->withErrors(['auth-validation' => 'ERROR: in validation!']);
}
Code in vew:
#if($errors->any())
#foreach($errors->getMessages() as $this_error)
<p style="color: red;">{{$this_error[0]}}</p>
#endforeach
#endif

The RedirectResponse class function withErrors() doesn't have a second parameter..
The function vendor\laravel\framework\src\Illuminate\Http\RedirectResponse.php -> withErrors():
/**
* Flash a container of errors to the session.
*
* #param \Illuminate\Support\Contracts\MessageProviderInterface|array $provider
* #return \Illuminate\Http\RedirectResponse
*/
public function withErrors($provider)
{
if ($provider instanceof MessageProviderInterface)
{
$this->with('errors', $provider->getMessageBag());
}
else
{
$this->with('errors', new MessageBag((array) $provider));
}
return $this;
}
So, if you really want to use the MessageBag then this should work (didn't test it):
$your_message_bag = new Illuminate\Support\MessageBag;
$your_message_bag->add('foo', 'bar');
return Redirect::back()->withInput()->withErrors($your_message_bag->all());

withErrors should receive the messages from validator object. After your validation process something like:
$validation = Validator::make(Input::all(), $validation_rules);
if (!$validation->passes()){
return Redirect::back()->withInput()->withErrors($validation->messages());
}
I hope it works fine for you.

You can write a function like this
if(!function_exists('errors_for')) {
function errors_for($attribute = null, $errors = null) {
if($errors && $errors->any()) {
return '<p class="text-danger">'.$errors->first($attribute).'</p>';
}
}
}
then in your View
<div class="form-group">
<label for="bio">Bio</label>
<textarea class="form-control" name="bio"></textarea>
</div>
{!! errors_for('bio',$errors) !!}
learnt from Jeffrey Way on Laracasts

Related

How to pass the chosen value in dropdownlist to controller tothen save

Hey guys please help help how can I pass chosen data in dropdownlist to controller to save then. Here is the code I am using:
The view:
<div class="form-group">
{{Form::label('IncomeExpense', 'Income&Expense')}}
{{Form::select('IncomeExpense', array( 'Expense', 'Income'),null,['class'=>'form-control'])}}
</div>
<div class="form-group">
{{Form::label('', 'Income')}}
{{Form::select('IncomeId', $incomes,null,['class'=>'form-control','id'=>'Income', 'onChange'=>'validate()'])}}
</div>
The controller:
$incexp= new IncomeExpenses();
$incexp->IncomeExpense=$request->input('IncomeExpense');
$incexp->save();
Model class
class IncomeExpenses extends Model
{
public function income(){
return $this->hasOne(Income::class);
}
public function expense(){
return $this->hasOne(Expenses::class);
}
}
EDIT
Try using $incexp->IncomeExpense=$request->IncomeExpense; instead of $request->input('IncomeExpense');
This is just like sending any other form, are you having trouble only with dropdowns ?
Your form open call should look something like this:
{!! Form::open(['method' => 'POST', 'url' => url('yourURL')] ) !!}
Depending on the version of Laravel 5... you will have to set the routes in the file routes.php or web.php
Route::post('yourURL', 'YourController#store');
Your store method should be something like
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'yourInput' => 'required',
]);
if ($validator->fails()) {
return redirect()->intended('yourURL')->withErrors($validator)->withInput();
}
DB::beginTransaction();
$incexp= new IncomeExpenses();
$incexp->IncomeExpense=$request->IncomeExpense;
$incexp->save();
DB::commit();
return redirect()->intended('yourURL/' . $incexp->id );
}

CakePhp 3.5 validation error mesages not showing on fields

so i started playing with a cakePhp app, trying to make it work, but i can't make the form helper output the validation error messages on the field with the error.I am using the FriendsOfCake/bootstrap-ui plugin to make the form helper output bootstrap forms.
Here is my model:
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->notEmpty('name', 'Name should not be empty')
->scalar('name')
->requirePresence('name', 'create');
return $validator;
My controller method:
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('V-ati inregistrat cu success'));
return $this->redirect($this->referer());
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->viewBuilder()->setLayout('auth');
$this->viewBuilder()->setTemplate('register');
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
and my form:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<?=
$this->Form->create('users',['url'=>['controller'=>'Users','action'=>'store']]),
$this->Form->control('name'),
$this->Form->control('email'),
$this->Form->control('password'),
$this->Form->submit('Trimite'),
$this->Form->end()
?>
</div>
</div>
You are passing an invalid context to the form helper. The $context argument of FormHelper::create() by default only supports false/null, an array, a result set, or an entity, and you want to pass the latter, ie the $user variable, which holds the entity that contains the possible validation errors.
$this->Form->create($user, [/* ... */])
See also
Cookbook > Views > Helpers > Form > Starting A Form

Laravel 5.1 passing data to mail view doesn't work

So, I'm trying to make an e-mail view, using data the user posted. The problem is, that specific data is unreachable. I don't know how I'm supposed to get that data.
Here is my controller:
public function PostSignupForm(Request $request)
{
// Make's messages of faults
$messages = [
//removed them to save space
];
//Validation rules
$rules = [
//removed them to save space
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
}
DB::table('rittensport')->insert([
'note' => $request->get('note'),
//standard instert
]);
/**
* Sending the e-mails to the pilot and co-pilot
*
* #return none
*/
Mail::send('emails.rittensport_signup', $request->all(), function ($message) {
$message->from(env('APP_MAIL'), 'RallyPodium & Reporting');
$message->sender(env('APP_MAIL'), 'RallyPodium & Reporting');
$message->to($request->get('piloot_email'), strtoupper($request->get('piloot_lastname')).' '.$request->get('piloot_firstname'));
$message->to($request->get('navigator_email'), strtoupper($request->get('navigator_lastname')).' '.$request->get('navigator_firstname'));
$message->subject('Uw inschrijving voor de RPR Gapersrit '. date('Y'));
$message->priority(1);//Highest priority (5 is lowest).
});
return Redirect::back();
Well, the view exists and the error I'm facing to is:
Undefined variable: request.
This is how I try to get the data in the e-mail view: {{ $request->get('note') }} I already tried things like {{ $message->note }}, $message['note'] And so on.
Try this:
Mail::send('emails.rittensport_signup', array("request" => $request), function (...

Laravel custom password validation

Hi gladly I want to use a custom validation rule for my textfield:
{{Form::label('password', 'Wachtwoord: ', array('class' => 'col-xs-4'))}}
<div class="col-xs-2">{{ Form::password('password', array('class' => 'form-control', 'placeholder'=>'Password')) }}</div>
And I already had followed the instructions on the following link: http://laravel.com/docs/4.2/validation#custom-validation-rules
But I get stuck when I want to use my custom validation.. I think that I have done something wrong in my code.
Gladly I would like to use the validatePassword() method (in validation.php) for my password textfield.
Here is my UserController.php:
public function update($id)
{
$user_old_data = User::find($id);
$input_password = Input::get('password');
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new validation($translator, $data, $rules, $messages);
});
/*Validator::extend('validatePassword', function($input_passwords,$input_passwords){
});*/
/*$validator = Validator::make($data = $thisUser, User::$rules);
if ($validator->passes()) {
if($user_old_data['email'] != $new_email){
$email_exists = User::FindEmailOrFail2(Input::get('email') );
if($email_exists)
return Redirect::back()->withErrors($validator)->withInput();
}
//maak message variabel aan in je user index view.
return Redirect::to('user/users')->with('message', 'Update with new password succesfull');
} */
return Redirect::back()->withErrors($validator)->withInput();
}
Here is my validation.php:
<?php
// app/validators/validation.php
class validation extends Illuminate\Validation\Validator
{
public function validateFoo($attribute, $value, $parameters){
//return $value == 'foo';
echo "this is the: " . $value;
}
//{4,} will match strings of length 4 or more.
protected function validatePassword( $attribute, $value ) {
return (bool) preg_match('/^[a-z]{4,}+$/', $value);
die('test');
}
}
If your code reflects the scope of your project you may not need a custom validator at all. You can use pattern:/^[a-z]{4,}$/ as one of your $rules in your User model.
You can see examples in Laravel's documentation: http://laravel.com/docs/4.2/validation#basic-usage
The pattern you used : /^[a-z]{4,}+$/ can be interpreted as "a string beginning with at least 4 characters matching lowercase a through z and a plus sign at the end of the string". Removing the plus sign (which regex is interpreting literally because of the quantifier before it) should make this work properly.
Remember to artisan optimize after you make changes to make sure the compiled.php is recompiled.

Laravel "Serialization of 'Closure' is not allowed"

When I go to store a dataset in Laravel, I sometimes get this error and haven't found a solution to it.
Serialization of 'Closure' is not allowed
Open: ./vendor/laravel/framework/src/Illuminate/Session/Store.php
*/
public function save()
{
$this->addBagDataToSession();
$this->ageFlashData();
$this->handler->write($this->getId(), serialize($this->attributes));
$this->started = false;
Here is the function being called when the error occurs:
public function store()
{
$data = Input::all();
$validator = array('first_name' =>'required', 'last_name' => 'required', 'email' => 'email|required_without:phone', 'phone' => 'numeric|size:10|required_without:email', 'address' => 'required');
$validate = Validator::make($data, $validator);
if($validate->fails()){
return Redirect::back()->with('message', $validate);
} else {
$customer = new Customer;
foreach (Input::all() as $field => $value) {
if($field == '_token') continue;
$customer->$field = $value;
}
$customer->save();
return View::make('admin/customers/show')->withcustomer($customer);
}
}
What is causing this serialization error?
Just replace following line:
return Redirect::back()->with('message', $validate);
with this:
return Redirect::back()->withErrors($validate);
Also, you may use something like this (To repopulate the form with old values):
return Redirect::back()->withErrors($validate)->withInput();
In the view you can use $errors variable to get the error messages, so if you use $errors->all() then you'll get an array of error messages and to get a specific error you may try something like this:
{{ $errors->first('email') }} // Print (echo) the first error message for email field
Also, in the following line:
return View::make('admin/customers/show')->withcustomer($customer);
You need to change the dynamic method to withCustomer not withcustomer, so you'll be able to access $customer variable in your view.
return Redirect::back()->with('message', $validate);
You are telling Laravel to serialize the entire validator object into session. To redirect with errors, use the withErrors method:
return Redirect::back()->withErrors($validate);
This will take the error messages out of the validator and flash those to session prior to redirecting. The way you're doing it now you're trying to store the entire class in Session which is causing your error.
Another issue I see is that I don't think there's a withcustomer method on the View class:
return View::make('admin/customers/show')->withcustomer($customer);
Try changing that to either just with:
return View::make('admin/customers/show')->with('customer', $customer);
or make sure to capitalize the Customer portion:
return View::make('admin/customers/show')->withCustomer($customer);
See also this question.

Categories