controller not recognizing data from view laravel 4.2 - laravel

hi so i have this function where the user edits a certain record. In my view, i already populated the input form it looks like this
behind the view here is my code
{{ Form::model($list, array('route' =>array('modfyFilesave',$list->subcategoryid , $list->fileid),'method'=>'PUT')) }}
<h6>Filename : </h6>
{{ Form::text('x', $list->filename , array('class' => 'validate')) }}
<h6>File type : {{ $list->filetype }} </h6>
#if($list->filetype == 'ppt' || $list->filetype == 'pptx')
<img src="{{ asset('img/ico/pptico.PNG') }}" class="imgico">
#elseif($list->filetype == 'doc' || $list->filetype == 'docx')
<img src="{{ asset('img/ico/wordico.PNG') }}" class="imgico">
#elseif($list->filetype == 'pdf')
<img src="{{ asset('img/ico/pdfico.PNG') }}" class="imgico">
#elseif($list->filetype == 'xls' || $list->filetype == 'xlsx')
<img src="{{ asset('img/ico/excelico.PNG') }}" class="imgico">
#elseif($list->filetype == 'txt')
<img src="{{ asset('img/ico/txtico.PNG') }}" class="imgico">
#elseif($list->filetype == 'csv')
<img src="{{ asset('img/ico/csvico.PNG') }}" class="imgico">
#endif
<h6>Size : {{ $list->filesize }} </h6>
#if($list->confidential == 'true')
{{ Form::checkbox('conf', 'true', true , array('id' => 'test5')) }}
<label for="test5">confidential</label>
#else
{{ Form::checkbox('conf', 'true', null , array('id' => 'test5')) }}
<label for="test5">confidential</label>
#endif
{{Form::select('sCategory',[ $list->subcategoryid =>'CURRENT CATEGORY : ' . $list->subcategoryname . ' | ' . $list->maincategoryname] + $cats )}}
{{ Form::submit('save', array('class' => 'btn btn-primary defcolor')) }}
{{ Form::close()}}
then the function that receive this is here
public function savemodfile($scid , $id)
{
$rules = array(
'x' => 'required|min:2|max:250|unique:nsa_fileuploads,filename'
);
$messages = array(
'x.required' => 'Please provide a filename.',
'x.min' => 'Filename should have atleast 2 characters.',
'x.max' => 'Filename can only have maximum of 250 characters.',
'x.unique' => 'Filename already exist.'
);
$validator = Validator::make(Input::all(), $rules , $messages);
if ($validator->fails())
{
dd('some errors');
}
else
{
dd('okay');
}
}
the thing is, it always go inside the if($validator->fails()) even tho in my view, there is data. anybody who could point out my error? or improve my code? thanks so much in advance!

Try dumping the errors the validator returns, the messages given should give you a direction what exactly failed when validating.
// dump errors
dd($validator->messages()->toArray());
For more information, see: https://laravel.com/docs/4.2/validation#error-messages-and-views

Related

Problems with Laravel Pivot Table

I am working on a medical lab application in laravel where I have the following tables:
1. Test table: This is a table which stores all the information related to medical tests:
2: Checkup: This is a page which contains all the patient information along with the tests he/she takes.
This is the test page:
This is the Checkup page where the tests and their results are selected:
Here can be many tests and user can check any number of them and will write the result of the test in the textfield below the checkbox.
I get this data in the controller like below code and save it to the database:
$this->validate($request,
[
'patient_name' => 'required|max:50',
'patient_age' => 'required',
'gender' => 'required',
'patient_type' => 'required',
'technition_id' => 'required',
'result' => 'required',
'test' => 'required',
'amount' => 'required'
]);
if( ($request->patient_type == 2) && ($request->doctor_id==0) )
{
return redirect()->back()->withInput(Input::all())->withErrors(['message' => 'Please select a valid Doctor.']);
}
$checkup = new Checkup;
$checkup->patient_name = $request->patient_name;
$checkup->patient_age = $request->patient_age;
$checkup->gender = $request->gender;
$checkup->patienttype_id = $request->patient_type;
$checkup->technition_id = $request->technition_id;
if(isset($request->doctor_id))
{
$checkup->doctor_id = $request->doctor_id;
}
$checkup->amount = $request->amount;
// $checkup->result = $request->result;
$checkup->save();
$tests =[];
$tests = $request->test;
$results =[];
$results = $request->result;
//$checkup->tests()->attach($tests->id, ['result' => $result]);
$sync_data = [];
for($i = 0; $i < count($tests); $i++)
$sync_data[$tests[$i]] = ['result' => $results[$i]];
$checkup->tests()->sync($sync_data);
Session::flash('success', 'The record was successfully saved.');
return redirect()->route('checkups.index');
Now the problem is that when I check all the checkboxes and write the result of all the tests then it is fine but when I select some and leave some of them then it gives error and the error comes because the result textbox for the unchecked test is empty.
This is the case when I select one test and leave the others:
When I check on test and write the result of it and then var_dump both test and result arrays i get the below output:
In the above image we can see that the test array contains one item because only one checkbox was checked but the result array contains two items and the first one is NULL which belongs to the unchecked checkbox.
This is the view file of the checkboxes and the textfields:
{{ Form::label('tests', 'Tests Taken') }}
#foreach(App\Test::all() as $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[]" type="text" class="form-control">
</div>
#endforeach
<div class="form-group">
{{ Form::label('amount', 'Amount') }}
{{ Form::text('amount', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{Form::button('<i class="fa fa-save"> Save</i>', ['type' => 'submit', 'class' => 'btn btn-success'])}}
</div>
{!! Form::close() !!}
Please help me on this and show me how to insert the pivot table data properly to the system.
Thanks in advance for any help.
Try this..
In your blade file :
#foreach(App\Test::all() as $index => $test)
<div class="checkbox checkbox-switchery">
{{ Form::label('test', $test->name) }}
<input name="test[{{ $index }}]" value="{{ $test->id }}" type="checkbox" class="switchery-primary">
</div>
<div>
{{ Form::label('result', "Result") }}
<input name="result[{{ $index }}]" type="text" class="form-control">
</div>
#endforeach
Instead of the for loop you can use foreach lopp.
$sync_data = [];
foreach($tests as $index => $value) {
if(!empty($results[$index]) {
$sync_data[$value] = ['result' => $results[$index]]
}
}
$checkup->tests()->sync($sync_data);

Update Data in Laravel

This is my code :
Route:
Route::get('/editposts/{id}', function ($id) {
$showpost = Posts::where('id', $id)->get();
return view('editposts', compact('showpost'));
});
Route::post('/editposts', array('uses'=>'PostController#Update'));
Controller :
public function Update($id)
{
$Posts = Posts::find($id);
$Posts->Title = 10;
$Posts->Content = 10;
$Posts->save();
//return Redirect()->back(); Input::get('Title')
}
and View:
#foreach($showpost as $showpost)
<h1>Edit Posts :</h1>
{{ Form::open(array('url'=>'editposts', 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ Form::submit('Update') }}
{{ Form::close() }}
#endforeach
but when I want to Update my data i receive an error :
http://localhost:8000/editposts/1
Missing argument 1 for App\Http\Controllers\PostController::Update()
You need to change route:
Route::post('editposts/{id}', 'PostController#Update');
Then the form to:
{{ Form::open(['url' => 'editposts/' . $showpost->id, 'method'=>'post']) }}
Change your post route to:
Route::post('/editposts/{id}', 'PostController#Update');
Done!
Correct the route,specify a parameter
Route::post('editposts/{id}', 'PostController#Update');
Pass the post'id as paramater
{{ Form::open(array('url'=>'editposts/'.$post->id, 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{
Form::submit('Update') }}
{{ Form::close() }}
Notice $post->id
First declare your route:
Route::post('/editposts/{id}', array('uses'=>'PostController#Update'));
Then update your form url:
{{ Form::open(['url' => url()->action('PostController#Update', [ "id" => $showpost->id ]), 'method'=>'post']) }}
This is assuming your model's id column is id
(Optional) You can also use implicit model binding :
public function Update(Posts $id) {
//No need to find it Laravel will do that
$id->Title = 10;
$id->Content = 10;
$id->save();
}

How to pass array to flash message?

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?
if(!empty($additional_features)){
foreach($additional_features as $additional_feature){
$data = [
'name' => $additional_feature,
];
if (!Feature::where('name', '=', $additional_feature)->exists()) {
$additional = Feature::firstOrCreate($data);
$additional_ids[] = $additional->id;
}
else{
return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
}
}
}
You can use session() instead of with():
session->flash('someVar', $someArray);
Another thing you could try is to seriallize array and pass it as string. Then unserilize it and use.
Also, you could save an array using simple session:
session(['someVar' => $someArray]);
Then get it and delete manually:
session('somevar');
session()->forget('someVar');
We had the same problem and forked the package. you can find it here:
Forked at first from Laracasts/Flash to use multiple message
#if (Session::has('flash_notification.message'))
#if (Session::has('flash_notification.overlay'))
#include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
#else
<div class="alert alert-{{ Session::get('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! Session::get('flash_notification.message') !!}
</div>
#endif
#endif
And the content of the include flash::modal
#if (Session::has('flash_notification.messages'))
#foreach (Session::get('flash_notification.messages') as $flashMessage)
#foreach($flashMessage as $type => $message)
<script>
$(function() {
var message = ('{{ $message }}<br>').replace(/'/g, "’");
customFlashMessage({
type: "{{ $type }}",
message: message
});
});
</script>
#endforeach
#endforeach
#endif
return redirect()->back()->with(['session1' => $value, 'session2' => $value]);
In the blade template:
{{ Session::get('session1') }}
{{ Session::get('session2') }}

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

Select Cascade Using jQuery and PHP in Laravel 4

I'm trying to populate a select box based on a previous select box value in Laravel 4. Here's what I have so far:
My JS:
var url = document.location.hostname + '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
alert(url);
label = "<label class='control-label'>Contacts</label>";
select = $("<select name='contact_id[]' id='contact_id'>");
console.log(contacts);
for(var i in contacts) {
alert(contacts[i]['account_id']);
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.contacts').html(select).prepend(label);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get()->toArray();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'view-only pull-left form-inline')) }}
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
{{ Form::select('account_id', $accounts) }}
<div class="contacts"></div>
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
{{ Form::select('delegate_status_id', $delegate_statuses) }}
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
{{ Form::text('price', '', array('class' => 'input-small')) }}
{{ Form::hidden('event_id', $event->id) }}
{{ Form::submit('Add Delegate', array('class' => 'btn btn-success')) }}
{{ Form::close() }}
EDIT: I've modified my code above. When I visit /list-contacts it gets the correct data I need, it's just not assigning that data to the contacts variable in my AJAX request in my JS? Any help would be appreciated.
Error: This is the error that is shown in my console log for the contacts variable:
file: "/Applications/MAMP/htdocs/cream/vendor/laravel/framework/src/Illuminate/Routing/Controllers/Controller.php"
line: 290
message: ""
type: "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
I now have this working. It was to do with the generated URL in the AJAX request. I removed the document.location.hostname and hard coded the url without localhost.
Here's the working code for those interested:
My JS:
var url = '/cream/public/list-contacts';
var contacts;
$.ajax({
async: false,
type: 'GET',
url: url,
dataType: 'json',
success : function(data) { contacts = data; }
});
$('#account_id').change(function() {
select = $("<select name='contact_id' id='contact_id'>");
for(var i in contacts) {
if(contacts[i]['account_id'] == $(this).val()) {
select.append('<option value="' + contacts[i]['id'] + '">' + contacts[i]['name'] + '</option>');
}
}
$('.delegates .contacts').show();
$('.delegates .contacts .controls').html(select);
});
My list-contacts route declaration:
Route::get('list-contacts', 'ContactListController#contacts');
My contacts() method in my ContactListController:
public function contacts()
{
return Contact::select('contacts.id', 'contacts.account_id', DB::raw('concat(contacts.first_name," ",contacts.last_name) AS name'))->get();
}
The form in my view:
{{ Form::open(array('action' => 'DelegatesController#store', 'class' => 'delegates pull-left form-horizontal add-delegate')) }}
<div class="control-group">
{{ Form::label('account_id', 'Account', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('account_id', $accounts) }}
</div>
</div>
<div class="control-group contacts">
{{ Form::label('contact_id', 'Contacts', array('class' => 'control-label')) }}
<div class="controls">
</div>
</div>
<div class="control-group">
{{ Form::label('delegate_status_id', 'Status', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::select('delegate_status_id', $delegate_statuses) }}
</div>
</div>
<div class="control-group">
{{ Form::label('price', 'Price', array('class' => 'control-label')) }}
<div class="controls">
{{ Form::text('price', '', array('class' => 'input-small')) }}
</div>
</div>
{{ Form::hidden('event_id', $event->id) }}
{{ Form::close() }}

Resources