How to send the values of checked items in a dynamic list from a database displayed in a view to controller? - laravel

How to send the values of checked items in a dynamic list from a database displayed in a view to controller ?

A concrete solution depends on your data, but if you are talking about a list of checkboxes, you can give them a common name in array notation:
<form type="post" action="...">
#foreach($elements as $elem)
<input type="checkbox" name="my_input[{{ $elem->id }}]" value="1">
#endforeach
</form>
On the server-side, you can then query the data like this:
use Illuminate\Http\Request;
class MyController
{
public function postData(Request $request)
{
$myInput = (array) $request->get('my_input', []);
// ... remaining logic
}
}
The line $myInput = (array) $request->get('my_input', []); will read the POST variable my_input as array and, if no such post variable is given, an empty array will be returned. In other words, $myInput will always be an array, where the key is $elem->id and the value '1' as defined by value="1".

Related

Livewire - updated hook without render of complex data

I'm using Livewire for data table with a complex database query with pagination. In table are also checkboxes and after check/uncheck is quite annoying to wait for render method with fetching all necessary data witch are required only for first component load.
I know I can use defer flag for checkboxes but I need also do some action when is any checkbox checked/unchecked so I cannot use that flag. So my question is if I can use updated hook method for checkbox without loading data in render.
Here is my example code:
class LivewireComponent extends Component
{
public $arrayOfCheckboxes = [];
public function render(SomeService $service)
{
$data = $service->fetchComplexData->paginate();
return view('livewire.some-component', ['data' => $data]);
}
public function updatedArrayOfCheckboxes($value)
{
// if value is true/false then do some action
// do I really need to call render and fetch complex data again?
}
}
// livewire.some-component.blade.php
<div>
<table>
#foreach($data as $row)
<input type="checkbox" wire:model="arrayOfCheckboxes" value="{{ $row->someValue }}">
#endforeach
</table>
</div>

Laravel Calling Multiple Controllers from Form Submit

I want to submit a form, and once that submit button is pressed, I run a bit of code.
During this 'bit of code', part of its job will be to create a student, and also create a lunch order. (information pulled from the form).
From what I've been reading, I should be aiming to use CRUD, which would mean I should have a Student Controller and a LunchOrderController.
I want to call the #store method in each controller.
If I was doing it the 'bad' way, the form would have [action="/students" method=POST]. And in that route, it would then call /lunchorder/ POST, and then return to a page (redirect('students')).
However, as above, I don't want to call a controller from a controller. Therefore, the initial [action="/students" method=POST] should be something else instead, and this new entity will then call the StudentController, then call the LunchOrderController, then redirect('students').
But, I don't know what this new entity is, or should be, or how to link to it.
It is just a new route to a new controller which is ok to call other controllers from?
Or is there some other place I should be sending the form data to (maybe models?), to them call the controller? Or am I way off base and need to take some steps back?
I'm fairly new to Laravel but am wanting to use best practice as much as possible. All my reading of other posts don't seem to explain it enough to get my head around how its meant to work.
Edit: Some code to give an idea of what I'm getting at.
Student_edit.blade.php
<form action="/student" method="POST">
{{ csrf_field() }}
<label>First Name</label><input name="firstname" value="">
<label>Last Name</label><input name="lastname" value="">
<label>Lunch Order</label>
<select name="lunch_value" id="">
<option value="1" >Meat Pie</option>
<option value="2" >Sandwich</option>
<option value="3" >Salad</option>
<option value="4" >Pizza</option>
</select>
<input type="submit" value="Submit" class="btn btn-primary btn-lg">
</form>
web.php
Route::resource('/students', 'StudentController');
Route::resource('/lunchorder', 'LunchOrderController');
Studentcontroller
public function store(Request $request)
{
Student::create(request(['firstname', 'lastname']));
LunchOrderController::store($request, $student_id); //<- This isn't the correct syntax
return redirect('/students');
}
LunchOrderController
public function store(Request $request, $student_id)
{
LunchOrder::create(array_merge(request(['lunch_value']), ['student_id' => $student_id]));
return null;
}
Personally I would create a 'Logic' Directory as: app/Logic. Some people prefer Repositories etc, but this is my preference.
For your specific requirement I'd create the following file:
app/Logic/StudentLogic.php
StudentLogic
<?php
namespace App\Logic\StudentLogic;
use App\Student;
use App\LunchOrder;
class StudentLogic
{
public function handleStudentLunch(Request $request): bool
{
$student = Student::create(request(['firstname', 'lastname']));
if(is_null($student)) {
return false;
}
LunchOrder::create(array_merge(request(['lunch_value']), ['student_id' => $student->id]));
return true;
}
}
StudentController
public function store(Request $request)
{
$logic = new StudentLogic();
$valid = $logic->handleStudentLunch($request);
if($valid) {
return redirect('/students');
}
abort(404, 'Student Not Found');
}
ASSUMPTIONS
Student is stored under App/Student & LunchOrder is stored under App\LunchOrder
You will also need to use App\Logic\StudentLogic in StudentController
The reason I'd split this out into a Logic file is because I do not like 'heavy' controllers. Also, I'm not entirely sure what you're trying to acomplish here, but creating a student on the same request you create a LunchOrder seems like you're asking for trouble

preg_replace() laravel -Insert array in database

I have this error :
ErrorException in helpers.php line 748:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
SerialController.php
public function createSerial(Request $request)
{
$serial = new Serial();
$serial->nume_serial = $request['numeSerial'];
$serial->claritate = $request['claritate'];
$serial->aparitie = $request['aparitie'];
$serial->genuri = $request['genuri'];
$serial->save();
return redirect('/admin');
}
view
<div class="checkbox">
SF<input type="checkbox" name="genuri[1]" value="sf" id="">
Biografic<input type="checkbox" name="genuri[2]" value="biografic" id="">
Animat<input type="checkbox" name="genuri[3]" value="animat" id="">
</div>
I guess a problem is you're trying to insert an array into a DB table.
$serial->genuri = $request['genuri']; // it's an array
You could convert an array to a json data:
$serial->genuri = json_encode($request['genuri']);
Of course you have to change genuri data type to JSON:
$table->json('genuri');
Apparently from looking at your view, $request['genuri'] is an array, and the error is this line $serial->genuri = $request['genuri']; since you are assigning an array to an object property that is string (I think?) in your DB table.
Not sure what you are trying to accomplish, if you provide more info I might help more.

Codeigniter: How do I pass multiple inputs with multiple same names?

First off, thank you for your valuable time and interest - any input to a beginner is greatly appreciated!
How do I insert multiple inputs with (in most cases) multiple same names? Here is my code:
View:
//Simplified version, original is a jquery append script
Passes: <input type="text" name="passes[]">
Points: <input type="text" name="points[]">
Passes: <input type="text" name="passes[]">
Points: <input type="text" name="points[]">
Controller:
//Loops through a table like form for inputting stats
function add_stat() {
$i = 0;
foreach ($this->input->post('points') as $points) {
$dataSet1[$i++] = array (
'points' => $points
);
}
foreach ($this->input->post('passes') as $passes) {
$dataSet2[$i++] = array (
'passes' => $passses
);
}
//Not sure how to pass multiple arrays, or if even possible
$this->sport_model->insert_stat($dataSet1, $dataSet2);
}
Model:
//Passing multiple params error out due to "String to Array Conversion"
function insert_stat($dataSet1, $dataSet2) {
$this->db->insert_batch('table', $dataSet1, $dataSet2);
return $this->db->insert_id();
}
set your controller and model as:
controller:
//Loops through a table like form for inputting stats
function add_stat() {
$points = $this->input->post('points');
$passes = $this->input->post('passes');
for($i=0;$i<sizeof($points);$i++)
{
$dataSet[$i] = array ('points' => $points[$i], 'passes' => $passses[$i]);
}
// $dataSet is an array of array
$this->sport_model->insert_stat($dataSet);
}
model:
function insert_stat($dataSet)
{
$this->db->insert_batch('table', $dataSet);
return $this->db->insert_id(); // this will return the id of last item inserted.
}
First, insert_batch() only takes two params: the table name and a data set.
Second, insert_id() isn't going to do you much good on a batch insert, but that's not a huge deal.
I assume you want points and passes to be in the same record, and that you're appending another set of points/passes inputs via JS.
View:
Passes: <input type="text" name="scores[0][passes]">
Points: <input type="text" name="scores[0][points]">
Passes: <input type="text" name="scores[1][passes]">
Points: <input type="text" name="scores[1][points]">
// etc...
In your controller, you would then just use one $dataSet array and loop through $this->input->post('scores')
When $dataSet is complete, you'd batch insert with $this->db->insert_batch('table', $dataSet)

Display db data in edit page

I am working with a registered_member_data_edit page?
My controller function is
function edit_profile()
{
$data['title']= 'Edit Profile';
$member_id = $this->session->userdata('member_id');
$this->load->model('user_model','',TRUE);
$data['row'] = $this->user_model->edit_user($member_id)->result();
$this->load->view('edit_profile.php', $this->data);
}
My model function is
public function edit_user($member_id)
{
$this->db->select('fullname','country','district','address','nominee_name','nominee_relation','mobile_no','password','bank_acc_no','bank_acc_name','bank_name','branch_name');
return $this->db->get_where('user', array('member_id'=> $member_id));
}
My view page is like
<p><label>User Name</label>
<input type="text" class="input-short" value="" /></p>
What should I put in the value to show the db data in edit page?
public function edit_user($member_id)
{
$this->db->select('fullname','country','district','address','nominee_name','nominee_relation','mobile_no','password','bank_acc_no','bank_acc_name','bank_name','branch_name');
return $this->db->get_where('user', array('member_id'=> $member_id));
}
this will return the object, which you have in $data['row'] and that variable you are sending to view file.
So in view file, you can access the all data of the object using $row.
So from here you have 2 options
Even that function returning only 1 row, you have to access using foreach($row->result() as $_data) and after that you can access each and every column as $_data->fullname like that.
You can convert that object to array using $row = $row->result_array() and you can access the database column using $row[0]['fullname'] like that.
Best luck.

Resources