Insert multiple entry using repository in Laravel - php

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,
]);
}
}

Related

How to inherit data from a create within the same store?

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
]);
}

Problem with the function update() using Repository pattern to write REST API

I have a problem that all the create-read-delete using Repository Pattern is good but the update function is error. I still have the data but the information is not updated.
This is my code in EventController
public function update(EventRequest $request, $id)
{
$events = $this->repository->update($request->all());
return $this->sendResponse($events->toArray(), 'Successfully updated the Event!!');
}
This is i use DI for inject from the Repository, this is EventRepository.php
public function update($id, array $array) {
$events = $this->model->findOrFail($id);
$events->update($array);
return $events;
}
when i use dd($array) and the result returns [] without anything. Can anyone help me. Did i write anything wrong in this. Or i write the wrong Request
public function rules()
{
// $id = $this->events ? ',' . $this->events->id : '';
return $rules = [
'event_title' => 'required|max:255',
'event_type_id' => 'required|integer|between:1,3',
'from_date' => 'required|date_format:Y-m-d H:i:s',
'to_date' => 'date_format:Y-m-d H:i:s|nullable',
'is_recurring' => 'boolean|required',
'remarks' => 'nullable',
];
}
This method takes two arguments:
public function update($id, array $array) {
However, that's not how you are calling it:
$this->repository->update($request->all());
I take it $request->all() gives you an array, so pass the ID first.
$this->repository->update($id, $request->all());

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();
}

Saving data from dynamic form in Laravel

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

Cluttered Controllers in Laravel 5.1

Is there a better way of organizing or writing the below controller method in Laravel 5.1?
I want to keep my Controllers short and sweet. I am using a repository setup as i'm building quite a large application and I want to keep everything organised.
Please advise on the best way to organise the below code.
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(CreateTimesheetRequest $request)
{
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row)
{
foreach($row as $field => $value)
{
$this->timesheet->saveTimesheetRows([
'timesheet_id' => $timesheetId,
'field_id' => $this->timesheetFields->where('name', $field)->first()->id,
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}
All I can suggest - move this:
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
... into yours request class. For example, into some data() method:
class CreateTimesheetRequest ... {
...
public function data() {
return array_merge(
$this->only('user_id', 'template_id'),
['submitted_by' => Auth::user()->id]
);
}
}
Also, $this->timesheet->saveTimesheetRows(array) looks more like $this->timesheet->saveTimesheetRow(array) for me - name intends to save multiple rows, but you feed that method only with one row per call.
Maybe, you can refactor that method to smth. like this:
function saveTimesheetRows($timesheetId, $key, $rows, $fieldIds) {
foreach($rows as $field => $value) {
$this->saveTimesheetRow([
'timesheet_id' => $timesheetId,
'field_id' => $fieldIds[$field],
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
function saveTimesheetRow(array $row) {
// old saveTimesheetRows implementation
}
Upd.
And another tip: use Eloquent's keyBy() method like so:
$keyIDs = $this->timesheetFields->whereIn('name', $fields)->get(["name", "id"])->keyBy("name");
So, finally:
public function create(CreateTimesheetRequest $request) {
$data = $request->data();
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row) {
$this->timesheet->saveTimesheetRows(
$timesheetId,
$key,
$row,
$this->timesheetFields
->whereIn('name', array_keys($row))
->get(["name", "id"])
->keyBy("name") // probably, can be moved into $this->timesheetFields implementation
);
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}

Categories