laravel Undefined offset: 0 - laravel

I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0

It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif

I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);

also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}

Related

Laravel Multiple Inputs Search 4.2

I am making a multiple inputs search query and i need help cause i do not know how to exactly to do this i have read all the documentation and i did not understand it.Now i am stuck in the controller.....
Also i would really appreciate of how to call the informations that i want in in the show.blade ! Thank you for any help !
Index blade
<div class="panel-body">
<div class="form-group">
<div><h4></h4></div>
<div class="form-group col-md-4">
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('name', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'name...')) }}
{{ Form::text('lastname', null, array('class' => 'form-group form-control', 'placeholder' => 'lastname...')) }}
{{-- {{ Form::text('id', null, array('class' => 'form-group form-control', 'placeholder' => 'id...')) }}
{{ Form::text('user-seminars', null, array('class' => 'form-group form-control', 'placeholder' => 'Class tha is enrolled...')) }}
{{ Form::text('user-class', null, array('class' => 'form-group form-control', 'placeholder' => 'Class that belongs...')) }}
{{ Form::text('user-annex', null, array('class' => 'form-group form-control', 'placeholder' => 'Department that belongs...')) }}
{{ Form::text('type', null, array('class' => 'form-group form-control', 'placeholder' => 'User type...')) }}
{{ Form::text('date_created', null, array('class' => 'form-group form-control', 'placeholder' => 'date created account...')) }}
{{ Form::text('date_enrolled', null, array('class' => 'form-group form-control', 'placeholder' => 'date enrolled in class...')) }}
routes
Route::get('users/index', 'UserController#index');
Route::get('users/search', 'UserController#search');
Route::get('users/show', 'UserController#show');
UserContoller
public function index(){
return View::make('user.index');
}
public function search(){
return View::make('user.show');
}
public function show(){
return View::make('user.show');
}
USERS TABLE
id , firstname,last_name,etc etc etc
public function search(Request $request){
$users = App\User::where('firstname',$request->name)
->orWhere('lastname',$request->lastname)
->orWhere('id',$request->id)
// more orWhere Clause
->get();
return View::make('user.show',compact('users'));
}
public function show($id){
$user = App\User::find($id);
return View::make('user.show',compact('user'));
}
Why are you using return View::make('user.show') to render two different resources?
the first thing i see its the form action
your code
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
should be
{{ Form::open(array('action' => array('users/search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
the controller is the fun part. if you're looking for all the inputs to be required you should validate it first
//first we set the inputs rultes
$data = Input::all();
$rules = array(
'name' => 'required',
'lastname' => 'required',
//rest of the inputs that are required
);
//then we use the validator method
$val = Validator::make($data,$rules);
if($val->fails())
{
/*redirect to the form again, you can set errors with session
or ->withError($validator)*/
return Redirect::back();
}
then you make your query
$user = User::where('name','=',$data['name'])
->where('lastname','=',$data['lastname'])
//more where('field','=','value')
->get();
if the fields arent required you only make the query with
$user = User::where('name','=',$data['name'])
->orWhere('lastname','=',$data['lastname'])
//more orWhere('field','=','value')
->get();
and finally you return your result to the view like:
return View::make('user.show')->with('user',$user);

toggle an html section on laravel 4.2 when using return Redirect

In my view i have this section where a user can add a new record to the database but the laravel form is inside a section where it is hidden by default here is my code in my view
<section id="anCity" style="display:none">
{{ Form::open(array('url'=> 'addCty')) }}
<div class="form-group">
{{ Form::label('ncty', 'City Name: ') }} <span style="color:red"><i>{{ $errors->first('ncty', ':message') }}</i></span>
{{ Form::text('ncty', Input::old('ncty'), array('class' => 'form-control','placeholder' => 'Insert City Name')) }}
</div>
{{ Form::submit('Add new City', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</section>
And inside my controller here is my code
$rules = array(
'ncty' => 'required|max:100|alpha_num'
);
$messages = array(
'ncty.required' => 'Please enter City Name.',
'ncty.max' => 'City Name can only have a maximum of 100 characters',
'ncty.alpha_num' => 'City Name can only contain alphanumeric characters'
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails())
{
return Redirect::to('lookup_board')
->withErrors($validator)
->withInput(Input::except('password'));
}
else
{
//insert new record
}
Is there a way to toggle the section on my view on the controller?
thanks
you can do it like:
<span class="#if($errors and $errors->has('ncty')) has-error #endif">{{ $errors->first('ncty') }}
I suppose you are using Twitter Bootstrap so it already has a class has-error for errors that you can use.
Replace your opening section tag with the following:
<section id="anCity"{{ ($errors->any() ? '' : ' style="display:none"') }}>

In Laravel what is the best method to save or store data in database

For usual Form like the following form I use the following technique to save data into database.
// Controller
public function store()
{
$validator = Validator::make($data = Input::all(), Person::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
Person::create($data);
return Redirect::route('admin.person.index');
}
But in my this form there is an file input field where user can upload multiple files at a time. and I want to store the files name into database i,e
image-1, image-2, image-3 like this. I am trying to use image intervention package to handle image files. But in that case what would my code to store data into database.
// Form
{{ Form::open(array('route' => array('admin.index.store'), 'method' => 'post', 'files' => true)) }}
<li>
{{ Form::label('name', 'Index Name') }}
{{ Form::text('name', null, array( 'class' => 'form-control input-sm', 'placeholder' => 'Name' )) }}
{{ $errors->first('name', '<p class="error">:message</p>' ) }}
</li>
<li>
{{ Form::label('phone_number', 'Phone Number') }}
{{ Form::text('phone_number', null, array( 'class' => 'form-control input-sm', 'placeholder' => 'Phone Number' )) }}
{{ $errors->first('phone_number', '<p class="error">:message</p>' ) }}
</li>
<li>
{{ Form::label('image', 'Profile Picture') }}
{{ Form::file('files[]', array('id' => 'files', 'multiple' => true)); }}
</li>
{{ Form::close() }}
Person::create($data); this wont fly.
You have to parse Input from forms, remove Files, process files separatelly and then update filepath with
//code to get $dataWithoutfiles;
$person = Person::create($dataWithoutFiles);
//code to save files to local
$person->file1 = 'path1';
// 2,3,4, etc.
$person->save();

Laravel validation throwing route error

I am attempting a basic validation check on form fields in the controller. The code is below:
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
The parameter passed to Redirect::to here is the folder members and registration view which resides in it. The problem is being caused by this line specifically:
return Redirect::to('members.registration')->withErrors($validator);
When it is commented out, form submission returns a blank white page. Otherwise the following error in the picture is shown
The route file has the following content:
Route::get('/', 'MainController#index');
Route::get('membersaccess', array('as' => 'membersaccess', 'uses' => 'MainController#loadMembersAccess'));
Route::get('signin', array('as' => 'signin', 'uses' => 'MembersController#loadlogin'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController#loadRegistration'));
Route::post('postLogin', array('as' => 'postLogin', 'uses' => 'MembersController#login'));
Route::post('postRegistration', array('as' => 'postRegistration', 'uses' => 'MembersController#registration'));
function containing the validation part is:
public function registration()
{
$email = Input::get('email');
$password = md5(Input::get('password'));
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
//echo $email;
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
}
and the form for reference:
#if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<h3> {{ $errors->first('email') }}</h3>
#endif
{{ Form::open(array('route' => 'postRegistration')) }}
{{ Form::text('email', null, array('placeholder'=>'Email', 'class' => 'randomfieldsize' ) ) }}
{{ Form::password('password', array('placeholder'=>'Password', 'class'=>'randomfieldsize' ) ) }}
{{ Form::text('firstname', null, array('placeholder'=>'First Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::text('lastName', null, array('placeholder'=>'Last Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::select('country', array('' => '', 'saudi' => 'Saudi Arabia', 'uae' => 'UAE')) }} <br><br>
{{Form::submit('Proceed', ['class' => 'button [radius round]'])}}
{{ Form::close() }}
Try this:
return Redirect::route('signup')->withErrors($validator);
You have no route defined as members.registration, so that may be the problem.
To show errors I usually use this (styling with bootstrap):
#if( $errors->has() )
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<ul>
#foreach ( $errors->all('<li>:message</li>') as $error )
{{ $error }}
#endforeach
</ul>
</div>
#endif
Edit: Ugh, didn't noticed it before, but your validation code is wrong. Please refer to http://laravel.com/docs/validation It should be something like this:
$email = Input::get('email');
$password = Input::get('password'); // Better to hash the password in another place, since md5 can create a hash even of an empty string. Also, please use laravel hash utility instead of md5: http://laravel.com/docs/security#storing-passwords
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
$validator = Validator::make(
compact('email', 'password', 'firstName', 'lastName', 'country'),
array(
'email' => 'required|min:7',
'password' => 'required|min:7'
'firstName' => 'required'
'lastName' => 'required'
));

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources