I have been trying to save data from dynamic form in Laravel 5.3. But I cannot save it as array. The error shows
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given...
Form:
<select class="form-control-sm" name="client_id[]">
<input type="text" class="form-control-sm" name="amount[]">
Model:
protected $fillable = ['client_id', 'amount'];
public function client()
{
return $this->belongsTo('App\Client');
}
Controller:
public function store(Request $request)
{
$count = Client::count();
$payment = Payment::create(['amount' => $request->amount,
'client_id' => $request->client_id,
]);
$payment->save();
return redirect()->action('PaymentController#index');
}
Please help on this. Thank you.
you are submitting form with array of text fields and select box, try
below
public function store(Request $request)
{
$count = Client::count();
foreach( $request->client_id as $key=>$val){
$payment = Payment::create(['amount' => $request->amount[$key],
'client_id' => $val,
]);
}
return redirect()->action('PaymentController#index');
}
Ty to create the record like this:
$payment = Payment::create($request->input);
And change you redirect action to this:
View::make('path/to/view/')
or just use just back(); just to test if it works
Related
I've 2 create in the same function store, but one field of the 1th create it must be the same of a field in the 2th create.
Is it possible?
DataController.php
public function store(Request $request)
{
SendData::create($request->validated());
// How I take here data from firt ::create ??
$random_data_from_form1 = ??
$data_from_form2 = $request->input('data_form2');
SendMoreData::create([
'field1' => $random_data_from_form1,
'field2' => $data_from_form2
]);
}
the create() method with return a new model instance of SendData.
You can update your code like this:
public function store(Request $request)
{
$new_object = SendData::create($request->validated());
// How I take here data from firt ::create ??
$random_data_from_form1 = $new_object->your_field;
$data_from_form2 = $request->input('data_form2');
SendMoreData::create([
'field1' => $random_data_from_form1,
'field2' => $data_from_form2
]);
}
The POST request I'm sending looks like this:
{ "array1":
[
{"title":"my blogADD","description":"myblogdescriptionADD","status":1},
{"title":"my blogUPDATEDADD","description":"myblogdescriptionUPDATEDADD","status":1},
{"title":"my blog33ADD","description":"myblogdescription33ADD","status":1}
]
}
Its JSON format, headers have been set.
The controller code which gets the request looks like this:
public function create(Request $request){
$this->validate($request, [
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->getContent();
$data = json_decode($data, true);
//dd($data);
Article::insert($data);
}
Now, I've looked into multiple questions and answers on SO on this problem, and the findings are somehow contradictory.
Model::insert() shall be able to insert multiple rows in ONE call.
However, as you can see, this hasn't worked for me so far.
Model::create() is only able to create one new row, but I found solutions which use loops to iterate over the arrays. I would very very much like to avoid such a solution, unless someone can FOR CERTAIN tell me that there is no other, simple solution. Because I very much believe that there must be one.
When I input the json_decoded ARRAY then I get the response that an Array to String conversion is hindering the process.
When I input the mere JSON-String, then I get the error:
"Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, string given, called in E:\LumenTut\firstTut\vendor\illuminate\database\Eloquent\Builder.php on line 1350"
Well, here are two links to SO posts which, in my opinion, basically dealt with the same problem. But somehow it seems they could solve it and I can't, so I wonder what I am missing:
How to insert a multidimensional array in a database using laravel
laravel 5.6 bulk inserting json data
For completeness, here is the full Code of ArticleController.php:
EDIT:
<?php
namespace App\Http\Controllers;
//use Validator;
use App\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//
}
//
public function showAllArticles(){
return response()->json(Article::get(['title', 'description', 'status'])); // ::get([]) spezifiziert die zu referenzierenden Attribute
// ::all() referenziert alle Attribute einer Tabelle/Relation
}
public function showOneArticle($id){
return response()->json(Article::find($id));
}
public function create(Request $request){
$this->validate($request, [
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->getContent();
//$data = json_decode($data, true);
//dd($data);
Article::insert($data);
}
public function update($id, Request $request){
$this->validate($request, [
'title' => 'required',
'description' => 'required'
]);
$article = Article::findOrFail($id);
$article->update($request->all());
return response()->json($article, 200);
}
public function delete($id, Request $request){
Article::findOrFail($id)->delete();
return response('Deleted Successfully', 200);
}
public function resetRecords(Request $request){
Article::where('id', '>', 2)->delete();
}
}
From the looks of it, it feels like you are trying to push array1 directly in your table, whereas you need to push the content of it so maybe try like this, in your controller code:
$requestData = $request->all();//this will give you an array with key array1
$data = $requestData['array1'];//this will give you data you want to insert
Article::insert($data);
Based on the error. You are not passing an array. You can change the $data with
$data = $request->all();
$request->all() returns the data from the post in array.
You can rewrite your create method with the following.
public function create(Request $request){
$request->validate([
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->all();
Article::insert($data['array1']);
}
I am working with laravel 5.5 to update entries. The problem is after changing the primary key 'id', which is elequoent default pk to 'project_id'. adding an item works fine but updating an item is not working properly. Here is the error I am getting.
Method save does not exist.
Here is my Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $primaryKey = 'project_id';
public function user()
{
return $this->belongsTo(User::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
}
Here is my controller function.
public function editProject($id){
$project = Project::where('project_id', $id)->firstOrFail();
$data = ["project_info" => $project];
return view('projects.edit')->with($data);
}
public function updateProject(Request $request){
$data = $request->all();
$validator = Validator::make($data, [
'project_title' => 'required',
'project_description' => 'required',
'project_start_date' => 'required',
'project_end_date' => 'required',
'project_status' => 'required',
]);
$response = [];
if ($validator->fails()){
$response["errors"] = [$validator->messages()->first()];
$response["success"] = false;
return json_encode($response);
}
else{
$project = Project::where("project_id", $request->input('project_id'))->get();
$project->project_title = $request->project_title;
$project->user_id = Session::get('user_id');
$project->project_description = $request->project_description;
$project->project_start_date = $request->project_start_date;
$project->project_end_date = $request->project_end_date;
$project->project_status = $request->project_status;
$project->save();
return redirect('/listProjects');
}
}
Using get() returns a collection. Despite the fact you are passing in a 'unique' ID, the project_id, it will still return a collection - the collection will simply have one element in it.
Subsequently, your code will not work as you have experienced, or at least not without a few changes to make $project reference the first element in the collection.
It's a quick fix though, just change this:
$project = Project::where("project_id", $request->input('project_id'))->get();
to this:
$project = Project::where("project_id", $request->input('project_id'))->first();
By using first(), eloquent will return the first element that matches the query and actually return the element (as opposed to a collection with one element) and so you can directly edit and save it.
Here is the solution I found.
$project_id = $request->input('project_id');
$project = Project::find($project_id);
$project->save();
You can find it by id using
Project::find($id);
Or get the first element like James said:
$project = Project::where("project_id", $request->input('project_id'))->first();
I want to input data to database. I am using Laravel 5. When I clicked the submit button. I got an error like the image below. Here is controller:`
public function tambahjenissurat(Request $request)
{ $this->validate($request, [
'jenis_surat' => 'required'
]);
$jenis_surat = $request['jenis_surat'];
$jenis_surat = new JenisSurat();
$jenis_surat->jenis_surat = $jenis_surat;
$jenis_surat->save();
return redirect()->route('jenissurat');
}`
Your code is expecting a string but you are passing an object. that could be the problem. try to give different names for object and variable. Something like this should fix the problem. See the lines below EDIT sections
public function tambahjenissurat(Request $request)
{ $this->validate($request, [
'jenis_surat' => 'required'
]);
**EDIT**
$jenis_surat_var = $request['jenis_surat'];
$jenis_surat = new JenisSurat();
**EDIT**
$jenis_surat->jenis_surat = $jenis_surat_var;
$jenis_surat->save();
return redirect()->route('jenissurat');
}
I wan to add the sector id to the request but when I submit the data nothing store on it.
Here is my code
public function store(QuestionRequest $request)
{
$data = $request->all();
Question::create($data);
$sectors = Sector::lists('id');
foreach($sectors as $sector){
CustomizeQuestion::create(array_add($request->all(), 'sector_id', $sector));
}
flash()->success('New question has been added.');
return redirect('questions');
}
I have tried this code also but it is the same :
public function store(QuestionRequest $request)
{
$data = $request->all();
Question::create($data);
$sectors = Sector::lists('id');
foreach($sectors as $sector){
$data['sector_id'] = $sector;
CustomizeQuestion::create($data);
}
flash()->success('New question has been added.');
return redirect('questions');
}
If you only want to add one 'id' to your request as you said, you can simply do this before creating anything :
$data = $request->all();
$data['sector_id'] = whatever you want;
Question::create($data);
Or like the second way you showed.
If this approach doesn't work verify if you have your properties specified in the model's fillable array and if you are using the correct property name as you specified in your migration.
First of all check your CustomizeQuestion model. sector_id should be in $fillable array. Example:
protected $fillable = [
'sector_id',
'more',
'and_more'
];
And if your form return only one id to store method no need to use foreach or list your id. Simply do this:
$data['sector_id'] = $request['id'];
CustomizeQuestion::create($data);