How to store array in Laravel? - php

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

Related

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

Laravel update array syntax

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

laravel call to a member function categories() on integer

I am trying to update and existing record in pivot table for many to many relationsip with laravel.
I have store function that work :
public function store(Request $request)
{
$produk = new product($request->input()) ;
$feat = (boolean)$request->input('featured');
$input = $request->all();
$input['featured'] = $feat;
$inputproduk = product::create($input);
$inputproduk->categories()->attach($request->input('kat_id'));
return redirect()->back()->with('message', 'Memasukkan Data Produk Berhasil');
}
But why my update function didn't work???
public function update(Request $request, $id)
{
$produk = Product::FindorFail($id);
$produk = new product($request->input()) ;
$input = $request->except('_method', '_token', 'picture', 'kat_id');
$inputproduk = product::whereId($id)->update($input);
$inputproduk->categories()->sync($request->input('kat_id'));
return redirect()->back()->with('message', 'Mengedit Data Produk Berhasil');
}
The error is :
Call to a member function categories() on integer
What is that mean? Please help me.
View :
<div class="form-group">
<label for="KategoriProduk">Kategori Produk</label>
<select class="form-control" name="kat_id[]" multiple>
#foreach($kategoris as $value)
<option value="{{$value->id}}">{{$value->namekat}}</option>
#endforeach
</select>
</div>
I only post partially because if I post it all then the question is just full of code. Tell me if you need more.
It's because of the following line.
$inputproduk = product::whereId($id)->update($input);
When you call update it will return an integer not a product object.
What you can do is first get the product and then update.
$inputproduk = product::whereId($id)->first();
$inputproduk->update($input);
$inputproduk->categories()->sync($request->input('kat_id'));

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

Updating database with laravel

Let me explain situation, person is searching through skills and when clicked displays list of handymans with that skill, when user clicks on one of them, full details are displayed. user then clicks assign job link and is taken to a page with jobs along with checkbox and when desired job is chosen, and submit button clicked, I want a database to update "job_id" value in "handymen" database. How could that be done?
#extends('layouts.master')
#section('title', 'Assign Job')
#section('content')
#section('content')
<form action="{{url('assignjob')}}" method="POST">
{{ csrf_field() }}
#foreach ($jobs as $job)
<div>
<label>{{$job->name}}</label>
<input type='checkbox' value='{{$job->id}}' name='jobs[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Assign Job">
</form>
#endsection
function search()
{
$skills = Skill::all();
return view('layouts/search',['skills' => $skills]);
}
function details($skillId)
{
$skill = Skill::find($skillId);
$handymen = $skill->handymen;
return view('layouts/details', ['skill' => $skill,'handymen' => $handymen]);
}
function assignJob($handymanId)
{
$assignJob = Hadnyman::find($handymanId);
$jobs = Job::all();
return view('layouts/assignjob',['jobs' => $jobs]);
}
function jobassign(Request $request)
{
return redirect('assignjob');
}
function skilledHandyman($handymanId)
{
$skilledHandyman = Handyman::find($handymanId);
return view('layouts/skilledHandyman', ['skilledHandyman' => $skilledHandyman]);
}
If a specific code is needed, please let me know
You should look at Eloquent Relationship.
Handymen has many Job
class Handymen extends Model {
...
public function jobs() {
return $this->hasMany(App\Job::class);
}
}
In your controller
function assignJob(Request $request, $id)
{
$handymen = Handyman::findOrFail($id);
// $request->get('jobs') = [1, 6, 7, etc...]
$handymen->saveMany($request->get('jobs'));
return ...;
}

Categories