Get method not supported, use post - php

I'm getting the error when I try to create a post and I don't know how to fix it since I just began using laravel and I'm still a noobie.
Route (web.php)
Route::put('/create_action', [App\Http\Controllers\ActionController::class, 'createAction'])->name('auditor.create_action');
This is my controller method:
public function createAction(Request $request) {
$sectors = \DB::table('sector')->get();
$risicosoorten = \DB::table('risicosoort')->get();
$risicoclassificaties = \DB::table('risicoclassificatie')->get();
$users = \DB::table('users')->where('name')->get();
$statussen = \DB::table('status')->get();
return view('auditor.create_action' , [
'sectors' => $sectors,
'risicosoorten' => $risicosoorten,
'risicoclassificaties' => $risicoclassificaties,
'users' => $users,
'statussen' => $statussen
]);
$actie->create([
'create_date' => $req->create_date,
'bron_detail' => $req->bron_detail,
'audit_oordel' => $req->audit_oordel,
'process' => $req->process,
'nummer_bevinding' => $req->nummer_bevinding,
'omschrijving_bevinding' => $req->omschrijving_bevinding,
'probleem' => $req->probleem,
'risico_beschrijving' => $req->risico_beschrijving,
'oorzaak' => $req->oorzaak,
'aanbeveling_ia' => $req->aanbeveling_ia,
'map' => $req->map,
'datum_deadline' => $req->datum_deadline,
'datum_bijgesteld' => $req->datum_bijgesteld,
'datum_gesloten' => $req->datum_gesloten,
'voortgang' => $req->voortgang,
'aantekeningen_ia' => $req->aantekeningen_ia,
'oordeel_ia' => $req->oordeel_ia,
'sector' => $req->sector,
'pr' => $req->pr,
'sr' => $req->sr,
'arc' => $req->arc,
'orc' => $req->orc,
'grc' => $req->grc,
'status' => $req->status,
'sub_status' => $req->sub_status
]);
}
my blade file with the form:
#extends('layouts.master')
#section('title')
#endsection
#section('content')
<div class="create_action" id="post">
<form action="{{ route('auditor.create_action') }}" method="POST">
#method('PUT')
#csrf
<form>
<div class="form-group">
<label for="creation_date">Datum ontstaan actie</label>
<input type="date" class="form-control" name="create_date">
</div>
<div class="form-group">
<label for="bron_detail">Bron detail</label>
<input type="text" class="form-control" name="bron_detail">
</div>
<button type="submit" class="btn btn-primary" name="submitBtn" value="submitPost"><strong>Maak actie aan</strong></button>
#endsection
and wayy more form input fields but trying to keep it as short as possible!

You have two opening form tags in your view. Right after the #csrf directive. Is this intentional? Because you can not nest form tags.
This may be what is causing your error because the application is trying to use the 'Get' method for the inner form tag since no method was stated.

Related

Laravel duplicate all fields of form using blade and insert multiple rows from a single query using eloquent

I want to have a add another form button that will duplicate all the fields of my form but will still remain one submit button and pass all the data of that into the controller to insert it using one single query.
Here is the create.blade.php that opens the form
#extends('encoder-dashboard.layouts.app')
#section('css')
<link rel="stylesheet" href="/css/datepicker.css">
#endsection
#section('content')
<section class="content-header">
<h1>
Add New Analysis Request
</h1>
</section>
<div class="content">
#include('adminlte-templates::common.errors')
<div class="box box-primary">
<div class="box-body">
<div class="row">
{!! Form::open(['route' => 'encoder.analysis-request.store']) !!}
#include('encoder-dashboard.analysis-request.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="/js/datepicker.js"></script>
<script>
$('#datepicker').datepicker({
autoclose: true
});
</script>
#endsection
And here are the fields listed in fields.blade.php
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('client_id', 'Client Name:') !!}
{!! Form::select('client_id[]', $client, null, ['class' => 'form-control','required'])!!}
</div>
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('sample_code', 'Sample Code:') !!}
{!! Form::text('sample_code[]', null, ['class' => 'form-control','required']) !!}
</div>
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('sample_description', 'Description:') !!}
{!! Form::text('sample_description[]', null, ['class' => 'form-control','required']) !!}
</div>
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('quantity', 'Quantity:') !!}
{!! Form::number('quantity[]', null, ['class' => 'form-control','required']) !!}
</div>
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('analysis_requested', 'Analysis Request:') !!}
{!! Form::text('analysis_requested[]', null, ['class' => 'form-control','required']) !!}
</div>
<!-- Password Field -->
<div class="form-group col-sm-6">
{!! Form::label('special_instruction', 'Special Instruction:') !!}
{!! Form::text('special_instruction[]', null, ['class' => 'form-control','required']) !!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-success', 'onClick' => 'this.form.submit(); this.disabled=true; this.value="Saving…";']) !!}
Cancel
</div>
All the fields above from the form will be duplicated and pass it as an array right? How do I do that maybe using jQuery or simple vanila JS as well?
and if I pass this data it would look like these.
array:8 [▼
"_token" => "xEGtr4h0f4gim0sLvABZivvq36UNaRHWJ08PMWTI"
"client_id" => array:1 [▼
0 => "1"
]
"sample_code" => array:1 [▼
0 => "eqwewqeqewqrwereqwe"
]
"sample_description" => array:1 [▼
0 => "dasdsadsadsadasd"
]
"quantity" => array:1 [▼
0 => "232"
]
"analysis_requested" => array:1 [▼
0 => "dsadsadsadsadsad"
]
"special_instruction" => array:1 [▼
0 => "dwqewqewqewqewqeq"
]
]
This is my query below when inserting one single record.
$analysis_request = $this->analysisrequestRepository->create([
'client_id' => $input['client_id'],
'sample_code' => $input['sample_code'],
'sample_description' => $input['sample_description'],
'quantity' => $input['quantity'],
'analysis_requested' => $input['analysis_requested'],
'special_instruction' => $input['special_instruction'],
'status' => 'for_testing'
]);
$id = $analysis_request->id;
$request_actors = RequestActors::create([
'request_id' => $id,
'encoder_id' => Auth::guard('encoder')->user()->id,
'microbiologist_id' => null
]);
this is my query above for inserting one single record. I also performed another query to insert the id of the request which has a relationship to the analysis request that is inserted in the first query.
Now if I will make it to insert many I will do an array inside an array and insert it each record right? Like this.
$data = array(
array(
'client_id' => $input['client_id'],
'sample_code' => $input['sample_code'],
'sample_description' => $input['sample_description'],
'quantity' => $input['quantity'],
'analysis_requested' => $input['analysis_requested'],
'special_instruction' => $input['special_instruction'],
'status' => 'for_testing'
),
// and so on.
);
AnalysisRequest::insert($data);
But I had an error in the code above it says that Array to string conversion
Or will it be better if I do an for each?
My only goal here is to perform an insert many query depends on the entries to add.
Appreciate if someone can help.
Thanks in advance.
You are getting an array of array and you want to put (for example) into client_id one array [1]
For that reason you have "Array to String conversion".
You can do
$data = array(
array(
'client_id' => $input['client_id'][0],
'sample_code' => $input['sample_code'][0],
'sample_description' => $input['sample_description'][0],
'quantity' => $input['quantity'][0],
'analysis_requested' => $input['analysis_requested'][0],
'special_instruction' => $input['special_instruction'][0],
'status' => 'for_testing'
),
// and so on.
);
AnalysisRequest::insert($data);

Iterate through an array of arrays with Mustache

I have checked all similar questions, no one seem to have answered this.
$data = ['data' => array(
['id'=>'1','name'=>'Dupe', 'country' => 'Nigeria'],
['id'=>'3','name'=>'Dipo', 'country' => 'Togo']
)];
$mustache->render('index', $data);
index.html looks like this:
<div>Hello</div>
<br>
<h2>Search for a person</h2>
<form action="/search" method="POST">
Input user's name or email:
<br><input type="text" name="key" value="" required>
<br>
<input type="submit" value="Search">
</form>
{{ #data }}
<div> {{ name }} - {{ country }} </div>
{{ /data }}
It is currently returning a blank page.
I couldn't figure that out, but converting the inner array to objects works just fine:
$m = new Mustache_Engine();
$data = [
'data' => array(
['id' => '1', 'name' => 'Dupe', 'country' => 'Nigeria'],
['id' => '3', 'name' => 'Dipo', 'country' => 'Togo']
)
];
$data = json_decode(json_encode($data));
echo $m->render(
'{{#data}}
<div> {{ name }} - {{ country }} </div>
{{/data}}',
$data
);
This outputs:
<div> Dupe - Nigeria </div>
<div> Dipo - Togo </div>
Notice {{#data}} and {{/data}} have no spaces!
I've used an inline template string as i didn't have yours.

Laravel image uploader

I'm trying to do a image upload on a form method but when i'm validating it always return an error saying the file is not an image. here you can see my html image uploader form:
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
and my controller where i'm making my validation:
$this->validate(request(),[
'nombre' => 'required|min:5',
'precio' => 'required|numeric',
'descripcion' => 'required|min:10',
'alto' => 'required|numeric',
'ancho' => 'required|numeric',
'largo' => 'required|numeric',
'categoria' => 'required|numeric',
'picture' => 'image|required',
]);
$store = new articulo();
$store->nombre = request('nombre');
$store->categoria_id = request('categoria');
$store->precio = request('precio');
$store->descripcion = request('descripcion');
$store->alto = request('alto');
$store->ancho = request('ancho');
$store->largo = request('largo');
$store->image = request('picture');
$store->save();
For image validation try this:
'picture' => 'mimes:jpeg,jpg,png|required'
You can also add max:5000 file size validation.
Hope that help
To upload an image your form must have the attribute enctype="multipart/form-data" so it submits the image as a file and not a string. Your form should be similar to this:
<form action="/yourroute" method="post" enctype="multipart/form-data">
....
<div class="row form-group">
<h4><strong>Imagen</strong></h4>
<input type="file" id="picture" name="picture" accept=".jpeg,.jpg,.png">
</div>
....
</form>

posted value is not displaying when use enctype as multipart/form-data in cakephp

I am working in cakephp.I have created one form that include file upload and textbox nad textarea.
Here, my html code looks like below :
<form action="" id="frmReg" method="post" enctype= "multipart/form-data">
<div style="position:relative; margin-bottom:30px;" class="fildtpart4">
<label><?php __d('statictext', 'Question', false); ?>:</label>
<span>
<textarea class="validate[required]" name="question1['question']" cols="" rows=""></textarea>
<div style="color: red; position:absolute ; bottom:-25px ;" id="charNum"></div>
</span>
<div class="clear"></div>
<div class="fildtpart3">
<label><?php __d('statictext', 'Currect Answer', false); ?></label>
<span>
<input name="question1['currect_ans']" type="text" class="validate[required]" id="" value="">
<input type="file" class="validate[required]" onchange="showMyImage1(this)" name="question1['sponsor_image']" id="" />
<input type="file" class="validate[required]" onchange="showMyImage2(this)" name="question1['question_image2']" id="" />
</span>
<input type="submit" value="submit" name="submit">
<div class="clear10"></div>
</div>
</div>
<form>
when I submit this form then it will shows only image not all data.
In my controller, I have written :
function add_polls()
{
print_r($this->params['form']);exit;
}
Then it gives output like :
array(
[question1]=>array(
[name] => Array
(
['sponsor_image'] => contact.jpg
['question_image2'] => contact.jpg
)
[type] => Array
(
['sponsor_image'] => image/jpeg
['question_image2'] => image/jpeg
)
[tmp_name] => Array
(
['sponsor_image'] => /tmp/phpUK7Vcj
['question_image2'] => /tmp/php3SCWGZ
)
[error] => Array
(
['sponsor_image'] => 0
['question_image2'] => 0
)
[size] => Array
(
['sponsor_image'] => 2305
['question_image2'] => 2305
)
)
)
Here, its not printed question1['currect_ans'] and question1['question'].When I remove enctype from the form then it will shows all value. So how can I resolve this problem?
Note: CakePHP vesrion is 1.3.13.
This is a mixture of how PHP handles files, and you not following the CakePHP conventions, causing CakePHP to "overwrite" your other form data.
You should use the form helper, that way you would avoid the problem in the first place, unless of course you'd fiddle with the field names and use such clashing ones again.
Adding everything in question1, including files, will result in the files being grouped under question1 in $_FILES, just as shown in your question, ie
Array(
[question1] => Array(
[name] => Array(
['sponsor_image'] => contact.jpg
['question_image2'] => contact.jpg
)
// ...
)
)
and the rest of the form data in $_POST using the same key, ie
Array(
[question1] => Array(
['question'] => 'foo',
['currect_ans'] => 'bar'
)
)
You should already smell the upcoming clash.
CakePHP will first fill $params['form'] with $_POST, and then iterate over $_FILES and use the keys to set the file data in $params['form'] too, which will lead to the previously set form data, ie the text inputs, to be overwritten, as both use the key, question1.
https://github.com/cakephp/cakephp/blob/1.3.13/cake/dispatcher.php#L248
https://github.com/cakephp/cakephp/blob/1.3.13/cake/dispatcher.php#L289-L293
tl;dr Follow the naming conventions, or use the form helper
Follow the CakePHP conventions and use the data key (and optionally a model name, which doesn't need to exist) to group the input, that way all data will be properly handled separately and made available via Controller::$data
name="data[question]"
name="data[currect_ans]"
name="data[sponsor_image]"
name="data[question_image2]"
No need to use quotes for nested keys btw.
Even better, as already mentioned, use the form helper, it will automatically create proper fieldnames.
See also
Cookbook > Core Helpers > Form > Field naming convention
Cookbook > Core Helpers > Form > File Fields
So i reproduced your issue and i'm reporting the following.
On my cakephp 3.x your form works great by submitting with 'regular' HTTP post. (I added an <input type="submit"> to your form).
[
'question1' => [
'question' => 'da',
'currect_ans' => 'da',
'sponsor_image' => [
'name' => 'Mobile version.png',
'type' => 'image/png',
'tmp_name' => '/tmp/php3A021O',
'error' => (int) 0,
'size' => (int) 149447
],
'question_image2' => [
'name' => 'Mobile version.png',
'type' => 'image/png',
'tmp_name' => '/tmp/phpi6VWxl',
'error' => (int) 0,
'size' => (int) 149447
]
]
]
So how are you submitting your data? Is it through ajax? What version of cakephp are you using? Try answering these questions so i can help you further on.
Have you tried getting the data using
$postedData = $this->request->data;

laravel form post instead of put

This is my form:
{{ Form::model($data, array(
'route' => array('waitingtimes.update', $data->id),
'class' => 'mainInformationContrainer',
'method' => 'put'
)) }}
When I submit the form, I got
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
though I've already set the request as put.
Could you help me please?
Edit 1
I noticed that the form html is
<form method="POST" action="http://localhost:8082/test/public/waitingtimes/2" accept-charset="UTF-8" class="mainInformationContrainer">
</form>
It is post not put,
Edit 2
The problem was because I mistyped the route to rout, but not I am getting this exception
Trying to get property of non-object
this is the view:
{{Form::model($data, array(
'route' => array('waitingtimes.update', $data->id)
, 'class' => 'mainInformationContrainer',
'method' => 'put'
))}}
<ul>
<li>
<label>First Time:</label>
<div class="oneInfo">
{{ Form::text('startTime', $value=null, array('class' => 'time ui-timepicker-input', 'id' => 'startTime', 'autocomplete' => 'off'))}}
<span class="errorMessage">
<?php
echo $errors->first('startTime');
?>
</span>
</div>
</li>
<li>
<label>End Time:</label>
<div class="oneInfo">
{{Form::text('endTime', $value=null, array('class' => 'time ui-timepicker-input', 'id' => 'endTime'))}}
<span class="errorMessage">
<?php
echo $errors->first('endTime');
?>
</span>
</div>
</li>
<li>
<label>Value:</label>
<div class="oneInfo">
{{Form::text('value', $value=null, array())}}
<span class="errorMessage">
<?php
echo $errors->first('value');
?>
</span>
</div>
</li>
<li>
<input type="submit" value="Save Changes"/>
<input type="button" value="Cancle" class="cancelButton"/>
</li>
</ul>
{{ Form::close() }}
this is the controller update
$input = Input::all();
$validation = Validator::make($input, WaitingTimes::$rules);
if ($validation->passes()){}else{
return Redirect::route('waitingtimes.edit')->withInput()->withErrors($validation)->with(array(
'verticalMenu'=>'none',
'verticalMenuTab' => 'none',
'data' => $input
));
}
Please notice that this html blade code is used for editing the data and it is working correct when I call the edit function, and I am using it also to redirect when the user try to edit information but the validation falls
You'll need to specify the method in your form creation, add this to your Form::model array:
'method' => 'PUT'
You will need to tell your form that you will be using method PUT:
{{ Form::model($data, array(
'route' => array('waitingtimes.update', $data->id),
'class' => 'mainInformationContrainer',
'method' => 'put',
)) }}
Note that you will still see method = "POST" in your form but Laravel will add a hidden field called _method to your form. See http://laravel.com/docs/html#opening-a-form
I found the solution,
which is
return Redirect::back()->withInput()->withErrors($validation)->with(array(
'verticalMenu'=>'none',
'verticalMenuTab' => 'none',
'data' => $input
));
Thanks to this question
Laravel form model binding

Categories