Displaying form elements obtained from database - laravel

I have a questions table which has a variety of questions of different input types. The format in my seeder is like so
DB::table('questions')->insert([
'name' => 'name',
'type' => 'text',
'text' => 'Name',
]);
DB::table('questions')->insert([
'name' => 'title',
'type' => 'select',
'text' => 'Title',
'values' => serialize(['Mr', 'Mrs', 'Ms']),
'class' => 'selectpicker'
]);
So you can see the above I have one text input and one select, which has serialized list of values. Now within my controller I get the Questions and pass it to my view.
Within my view, I am doing something like the following
#foreach($questions as $q)
<div class="col-xs-12">
<input type="{{ $q["type"] }}"
class="form-control {{ $q["class"] }}"
id="{{ $q["name"] }}"
name="questions[{{ $q["id"] }}]"
>
</div>
#endforeach
Where I am having difficulty is with the select inputs. How would I go about displaying my selects along with their options (values)?
Thanks

To create a list you can check the type of $q in your foreach. The code inside your loop would look like this:
#if( $q['type'] === 'select' )
<select name="questions[{{ $q['id'] }}]">
#foreach( unserialize($q['values']) as $v )
<option value="{{ $v }}">{{ $v }}</option>
#endforeach
</select>
#endif

Related

set permission to role spatie/laravel-permission

I'm trying to use this library and set permission to my users. I'm reading documentation and I created my roles. I set my array in input with name.
#foreach ($allPermission as $permission)
<div class="col-md-2">
<label class="form-check-label mr-4" for="{{ $permission->id }}">{{ $permission->name }}</label>
<input class="form-check-input" name="permission[]" type="checkbox" id="{{ $permission->id }}" value="{{ $permission->name }}">
</div>
#endforeach
In my controller, I received this:
Array ( [0] => show [1] => create [2] => destroy )
I'm trying to set this permissions with this:
$user = User::where("id", $id)->update([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => \Hash::make($request->get('password')),
]);
// update permissions to user
$user->givePermissionTo($request->get('permission'));
this returns...
Call to a member function givePermissionTo() on int
I'm trying to set permissions with id and with name and getting same error.
$user = User::where("id", $id)->update([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => \Hash::make($request->get('password')),
]);
return $user is count records was updated ($user of you is not a collection)
you can use :
$user = User::find($id);
then
$user->givePermissionTo($request->get('permission'));

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"') }}>

Laravel : I am trying to pass a variable from view to controller but it returns null

This is My View code When i am executing the application it only returns me NULL value, basically my $office_category is not being passed, i need the office category to query the database
<div class="box-body">
{{ Form::open(['route' => 'office.index','class' => 'form-horizontal office-form']) }}
<div class="form-body">
<div class="form-group">
<div class="col-md-3">
{{ Form::select('office_category', [
null=>'Please Select',
'Software' => 'Software',
'Computer Hardware' => 'Computer Hardware',
'Survey Instruments' => 'Survey Instruments',
'Office Equipments' => 'Office Equipments'
], isset($office_category) ? $office_category : '', ['class' => 'form-control input-xlarge select2me', 'placeholder' => 'Project Type', 'id' => 'office_category'] ) }}
</div>
{{ Form::hidden('office_category', $office_category) }}
{{ Form::submit('Search Equipment',['class' => 'btn green']) }}
</div>
</div>
{{ Form::close() }}
My Controller Code: I want the Office category thats it
Class OfficeController extends BaseController{
public function index(){
$office_category = Input::get('office_category');
if($office_category=='')
$offices = Office::orderBy('office_category', 'asc')
->get();
else
$offices = Office::where('office_category','=',$office_category)
->get();
$assets = ['table','datepicker'];
$users = User::where('client_id','=','')
->orderBy('name','asc')
->lists('name','username');
return View::make('office.index',[
'office_category' => $office_category,
'offices' => $offices,
'users' => $users,
'assets' => $assets
]);
}
Where am i going wrong please help.
You have a hidden field directly after your select that has the same name as the select. The value of this hidden field (empty) is what is getting sent to the server.
Delete this line:
{{ Form::hidden('office_category', $office_category) }}
Or rename this hidden field.
By default Form::open creates a POST request and your index method on Controller are expecting a GET request.
You need to add a new route on routes.php to match this POST request.
Route::post('index', 'OfficeController#index');
Or if you don't mind, you can set index to listen any kind of request:
Route::any('index', 'OfficeController#index');
In most of the case, above answer will solve your problem. If not, you can inspect your web request from browser and confirm value in $office_category variable.

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 Undefined offset: 0

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
}

Resources