Laravel update array syntax - php

I'm having trouble doing a record update array via POST in Laravel.
I have captured all the post data in an array cant update array achievement
<form action="{{'updateapp'}}" method="post">
<table>
<tr><td>
<input type="checkbox" class="id" name="id[]" value="{{ $quarter->id }}" />
<input type="text" name="achv[]" value="{{ $quarter->achievement }}">
</td></tr>
</table>
</form>
Controller :
public function foo(Request $request)
{
$ids = $request->id;
$achvs = $request->achv;
DB::table('quarters')->whereIn('id', $ids)
->update(array(['achievement' => $achvs ]));
return redirect('evaluator');
}

As you have set [] array in your form, you can access it as following
public function foo(Request $request)
{
$ids = $request->id[0];
$achvs = $request->achv[0];
DB::table('quarters')->where('id', $ids)
->update(['achievement' => $achvs ]);
return redirect('evaluator');
}
if you want to update multiple rows then use following code:
foreach($request->id as $key => $value){
$quarters = Quarters::find($request->id[$key]);
$quarters->achievement = $request->achv[$key];
$quarters->save();
}

public function foo(Request $request)
{
$ids = $request->id[0];
$achvs = $request->achv[0];
DB::table('quarters')->where('id', $ids)
->update(array(['achievement' => $achvs,'achievement1' => $achvs1]));
return redirect('evaluator');
}

Related

How check if id exist in database before return?

Before looking for a page I wanted to check if the id exists, so if I don't find it, give up looking I tried as follows:
My controller product
public function search(Request $request)
{
$id = $request->input('id');
if($produto = Produto::find($id)) {
return view('produtos.show', compact('produto', 'id'));
}
// $search_results=Produto::findOrFail($id);
return 'Not found';
}
->My Route->
Route::get('/produtos/editar/{id?}','App\Http\Controllers\ProdutosController#search')->name('searchproduct');
->My Blade Form
<form id="search" method="GET" action="{{ route('searchproduct') }}" >
<input id="q" name="q" type="text" /></br>
<button type="submit" id="submitButton" >Alterar</button>
</form>
</div>
</div>
</div>
</div>
->My Jquery Script
jQuery(document).ready(function(){
jQuery("form#search").on('submit',function(e){
e.preventDefault();
var q = jQuery("#q").val();
window.location.href = jQuery(this).prop('action')+"/" + encodeURIComponent(q)
});
});
How can i check in database before? send It's always going to the default 404 page
It's enough to check $search_results variable. I changed findOrFail with find because findOrFail may throw an error.
public function search(Request $request) {
$search_results = Produto::find($request->input('id'));
if ($search_results == NULL) {
abort(404);
}
return view('produtos.show', ['produto' => $search_results, 'id' => $request->input('id')]);
}
Also yo can use:
public function search(Request $request) {
$search_results = Produto::where('id', '=', $request->input('id'))->first();
if ($search_results == NULL) {
abort(404);
}
return view('produtos.show', ['produto' => $search_results, 'id' => $request->input('id')]);
}
Two ways to go about it:
exists:
if (Produto::where('id', $id)->exists()) {
$search_results=Produto::find($id);
}
findOr:
$search_results = Produto::findOr($id, function () {
// whatever you want to do if no record is found
});
to show a 404 page use this code :
public function search(Request $request)
{
//if not found it will trigger 404 not found page
$produto = Produto::findOrFail($id = $request->input('id'));
//otherwise it will return the view of produtos.show
return view('produtos.show', compact('produto', 'id'));
}
or you can use this code too to use a custom return
public function search(Request $request)
{
$id = $request->input('id');
if($produto = Produto::find($id)) {
return view('produtos.show', compact('produto', 'id'));
}
//otherwise return your error view or message
return 'Not found';
}
-> your route must be get not post
Route::get('/produtos/editar/{id?}','ProdutosController#search')->name('searchproduct');
-> no need for #csrf for get method
<form id="search" method="GET" action="{{ route('searchproduct') }}" >
<input id="q" type="text" /></br>
<button type="submit" id="submitButton" >Alterar</button>
</form>

Laravel 8: Function params must be an array

I have a route that must get some parameters:
Route::get('users/{function}/{param}/{feeLimit}/{callValue}/{bandwidthLimit}' , [TronController::class, 'totalUsers']);
And the method totalUsers looks like this:
public function totalUsers($function,$params,$feeLimit,$callValue,$bandwidthLimit){
And in the browser, I call it like this:
http://localhost:8000/users/totalUsers/array()/30000000/0/0
But now I get this error:
Function params must be an array
I know this way of adding parameters is wrong, but I don't how to call the url and variables like this on the browser:
$function="totalUsers";
$params=array();
$feeLimit=30000000;
$callValue = 0;
$bandwidthLimit = 0;
How can I call totalUsers method properly with its parameters?
Update 1
In the method totalUsers:
try {
$trigger = $TransactionBuilder->triggerSmartContract(
(array)$abi,
$contractH,
$function,
$params,
$feeLimit,
$addressH,
$callValue = 0,
$bandwidthLimit = 0);
var_dump($trigger);
} catch (\IEXBase\TronAPI\Exception\TronException $e) {
die($e->getMessage());
}
Easily You can solve this problem by using this route as post:
Route::post('/users' , [TronController::class, 'totalUsers'])->name('users');
Then you can send the value by submitting a form:
<form action="{{ route('users') }}" method="post">
#csrf
<input type="text" name="function" />
<input type="text" name="params[]" />
<input type="text" name="params[]" />
<input type="text" name="params[]" />
.... // how much you want
<input type="text" name="feeLimit" />
<input type="text" name="callValue" />
<input type="text" name="bandwidthLimit" />
<input type="submit" value="Send">
</form>
You will be getting an array for this params field, this is secure and you can send a large number of data character:
In the controller:
public function totalUsers(Request $request)
{
$function=$request->function;
$params=$request->param; // this will be an array
$feeLimit=$request->feeLimit;
$callValue = $request->callValue;
$bandwidthLimit = $request->bandwidthLimit;
foreach( $params as $param )
{
$param; // do what ever you want
}
}
Your error has nothing to do with routes, it's a tron-api's error. The triggerSmartContract() function expects $params to be an array, but you're passing a string.
Easy way to solve that would be just convert your $params string to array in the arguments (array)$params.
Correct way would be to follow advice in this answer, though I'd suggest to validate user input:
public function totalUsers(Request $request)
{
$request->validate([
'function' => 'required|string',
'params' => 'required|array',
'feeLimit' => 'required|numeric',
'callValue' => 'sometimes|numeric',
'bandwidthLimit' => 'sometimes|numeric',
]);
try {
$trigger = $TransactionBuilder->triggerSmartContract(
(array)$abi,
$contractH,
$request->input('function'),
$request->input('params'),
$request->input('feeLimit'),
$addressH,
$request->input('callValue', 0),
$request->input('bandwidthLimit', 0)
);
var_dump($trigger);
} catch (\IEXBase\TronAPI\Exception\TronException $e) {
die($e->getMessage());
}
}

Insert multiple entry using repository in Laravel

I using repository to insert data
public function create(array $data)
{
return $this->model->create($data);
}
It works fine when I add single data in form
<input type="text" class="form-control" name="name">
using store method in controller
public function store(Request $request)
{
$this->model->create($request->only($this->model->getModel()->fillable));
}
However, if I try to add multiple data it is not working
<input type="text" class="form-control" name="name[]">
In this case, I can store multiple data in this way
public function store(Request $request)
{
foreach ($request->user_id as $key => $val) {
$this->model->create([
'name' => $request->name[$key],
'description' => $request->description[$key],
'user_id' => $request->user_id[$key],
]);
}
}
Can you please suggest how my store method in controller should be so that it can accept array of data using repository?
Get request data into a variable $input and then insert using foreach loop.
public function store(Request $request) {
$input = $request->all();
foreach ($input['user_id'] as $key => $val) {
$this->model->create([
'name' => $input["name"][$key],
'description' => $input["description"][$key],
'user_id' => $val,
]);
}
}

How to store array in Laravel?

There are two mysql tables 1.seats (id,number), 2.reservedseats(id,seat_id,sceering_id).
I show all the seats of a specific sceering as checkboxes in show.blade:
{!!Form::model($screening,['method'=>'post', 'action'=>
['ReserveController#store',$screening->auditorium->id]])!!}
<input type="hidden" name="screening_id" value="{{$screening->id}}">
#foreach($seats as $seat)
<label class="checkbox-inline">
{!!Form::checkbox('seat_id[]',$seat->id,null)!!} Number: {{$seat->number}}
</label>
#endforeach
<div class='form-group'>
{!!Form::submit('Create Post',['class'=>'btn btn-primary '])!!}
</div>
{!!Form::close()!!}
When I click a checkbox it goes the the seat_id[] array. So I send a hidden input and an array with the seat_ids then I want to store in the reservedseats Mysql table. But in the store controller I have the problem. I'm trying something like:
public function store(Request $request){
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
foreach($seat_ids as $seat_id){
Seatreserved::create($seat_id,$screening_id);
}
}
So it not working but how can I solve that?
Try this code
public function store(Request $request)
{
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
foreach($seat_ids as $seat_id) {
Seatreserved::create([
'seat_id' => $seat_id,
'screening_id' => $screening_id
]);
}
}
Also you can use
public function store(Request $request)
{
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
$data = [];
foreach($seat_ids as $seat_id) {
$data[] = [
'seat_id' => $seat_id,
'screening_id' => $screening_id
];
}
Seatreserved::insert($data);
}
That is better way to perform this as it will interact with database for once.
You can also create a new instance of your model to store values.
Example:
foreach($seat_ids as $seat_id) {
$reserved = new Seatreserved();
$reserved->seat_id = $seat_id;
$reserved->screening_id = $screening_id;
$reserved->save();
}

Laravel store value from for-each loop and passed it as array

I have two for-each loop inside my create view [Subject_id, Lead_id], I want to store the for-each value into my database using array approach, and I couldn't make it work can anyone amend my codes or point me to a proper way thanks.
Controller:
public function store(Request $request)
{
//
$input = $request->all();
$items = array(['Subject_id','Lead_id']);
foreach($input as $inputs) {
$items[] = $inputs;
}
$scores = new Score();
$scores->Subject_id=$items['Subject_id'];
$scores->Lead_id=$items['Lead_id'];
$scores->save();
dd($request->all());
return redirect()->route('scores.create')->with('notif', 'Success.');
}
this is the message:
create view
#foreach ($leads as $lead)
<tr>
<td>{{ $lead->student_name }}</td>
<td><input type="checkbox" class="checkbox" name="Lead_id[]" value="{{ $lead->id }}"></td>
</tr>
#endforeach
#foreach($subjects as $subject)
<label >
<input type="checkbox" name="Subject_id[]" value="{{ $subject->id }}">
{{ $subject->subject_name }}
</label>
#endforeach
DD Result:
Try this code in your controller
public function store(Request $request)
{
$data = $request->all();
$leads = $data['Lead_id'];
$subject_ids = $data['Subject_id'];
//insert using foreach loop
foreach($leads as $key => $input) {
$scores = new Score();
$scores->Subject_id = isset($leads[$key]) ? $leads[$key] : ''; //add a default value here
$scores->Lead_id = isset($subject_ids[$key]) ? $subject_ids[$key] : ''; //add a default value here
$scores->save();
}
//insert using array at once
$rows = [];
foreach($leads as $key => $input) {
array_push($rows, [
'Subject_id' => isset($leads[$key]) ? $leads[$key] : '', //add a default value here
'Lead_id' => isset($subject_ids[$key]) ? $subject_ids[$key] : '' //add a default value here
]);
}
Score::insert($rows);
return redirect()->route('scores.create')->with('notif', 'Success.');
}
Every time creating an instance of model in foreach loop in not an efficient way. You can do something like this
foreach($input as $inputs) {
$dataArray[] = [
'Subject_id' => $inputs['Subject_id'],
'Lead_id' => $inputs['Lead_id'],
];
}
DB::table('Score')->insert($dataArray);
You can manipulate the data as you want.
with this code i have this
Update your blade
#foreach ($leads as $lead)
{{ $lead->student_name }}
#foreach($subjects as $subject)
<input type="checkbox" name="Subject_id[$lead->id][]" value="{{ $subject->id }}">
{{ $subject->subject_name }}
#endforeach
#endforeach
This as your controller
public function store(Request $request)
{
//
$subjects = $request->get('Subject_id');
foreach($subjects as $key=>$oneLeadOptions) {
foreach($oneLeadOptions as $option){
$scores = new Score();
$scores->Subject_id = $option;
$scores->Lead_id = $key;
$scores->save();
}
}
//To to other redirects logic here
}
try this

Categories