How to insert multiple rows into a table at one time? - php

I need to send e.g. 5 records in one query into the one table (id_book - is every time different), so I need to by one click on button, create e.g. 10 records. This code shows this Error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id_book.0' in 'where clause' (SQL: select count() as aggregate from connect_user_books where id_book.0 = 6* (MY TEXT: 6 IS ID OF MY LIST INTO WHICH I NEED TO ADD THEASE RECORDS))
My controller:
public function create()
{
$books = Book::all();
return view('connectUserBook.create', compact('books'));
}
public function store(Request $request)
{
$this->validate($request, [
'id_user_select' => 'required',
'id_book' => 'required|array',
'id_book.*' => 'exists:connect_user_books',
]);
$userId = $request->input('id_user_select');
// Vytvoření
foreach ($request->input('id_book') as $book) {
$connect = new ConnectUserBook;
$connect->id_user_select = $userId;
$connect->id_book = $book;
$connect->save();
}
return redirect('/dashboard')->with('success', 'Výběr editován!');
}
My HTML markup:
{{ Form::open(['action' => 'ConnectUserBookController#store', 'method' => 'POST']) }}
<div>
<label class="form-label">Vybraný výběr *</label>
<div>
<select name="id_user_select" class="form-control">
<?php
$select_id = $_GET["id"];
$select_id;
$res = mysqli_query($link, "select * from selected_books Where id = $select_id");
while($row = mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"]; ?>"> <?php echo $row["title"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<br>
#for ($i = 0; $i < 11; $i++)
<div>
<label class="form-label">Book {{ $i }} *</label>
<div>
<select name="id_book[]" class="form-control">
#foreach ($books as $book)
<option value="{{ $book->id_book }}">{{ $book->nazev }} - {{ $book->pocet_stranek }} stran</option>
#endforeach
</select>
</div>
</div>
#endfor
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
{{ Form::close() }}

Make an array and use the insert method with eloquent.
$data = array()
foreach ($request->input('id_book') as $book) {
$data[] = array('id_user_select'=>$userId,'id_book'=>$book);
}
ConnectUserBook::insert($data);
as per your error your need to specify with the column. add a column to compare with which column exists?
'id_book.*' => 'exists:connect_user_books,column_name',
Note :- It doesn't insert the timestamps.

Related

Laravel: Let user select MODEL and then get query

I am working on a Laravel project, which should be somewhat modular.
I have written a search query and what I want is following:
Models:
Assessment A
Assessment B
Assessment C
View:
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
<option value="assessment_a">A</option>
<option value="assessment_b">B</option>
<option value="assessment_c">C</option>
</select>
{{ Form::close() }}
Controller:
The controller is much more complex but I made it easier for you to understand what my need is.
Now something like follows:
$user_entry =$request->input('search_by_form', []);
$resultArray = [];
foreach ($user_entry as $entry){
if ($entry == "assessment_a"){
$model_results = AssessmentA::where("approved",1)->get();
} elseif ($entry == "assessment_b"){
$model_results = AssessmentB::where("approved",1)->get();
} elseif($entry == "assessment_c"){
$model_results = AssessmentC::where("approved",1)->get();
}
}
What I want:
SearchViewController:
foreach through Models in specific folder
then:
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
#foreach($models as $model)
<option value="{{ $model }}">{{ $model->name }}</option>
#endforeach
</select>
{{ Form::close() }}
Instead of having such an ugly approach is it possible to have more something like this:
foreach ($user_entry as $entry){
$entry::where("approved",1)->get(); #Obviously the values on the view would be change to "AssessmentA", etc.
}
I this feasible?
Thank in advance!
I think you will create any array like this:
$model_array = ['assessment_a' => AssessmentA::class];
Then in loop simply pass value
foreach ($user_entry as $entry){
$model_array[$entry]::where("approved",1)->get(); #Obviously the values on the view would be change to "AssessmentA", etc.
}
If you change the select values to the actual table names, you could do it easily
{{ Form::open(array('route' => 'search')) }}
<select multiple name="search_by_form[]">
<option selected>Any</option>
<option value="assessments_a">A</option>
<option value="assessments_b">B</option>
<option value="assessments_c">C</option>
</select>
{{ Form::close() }}
$user_entry = $request->input('search_by_form', []);
if (empty($user_entry)) {
model_results = collect();
} else {
$query = DB::table(array_shift($user_entry))->where('approved', 1);
foreach ($user_entry as $table) {
$query->union(fn($union) => $union->from($table)->where('approved', 1));
}
$model_results = $query->get();
}

How to save array data from multiple select in Laravel using Eloquent

i'd like to save data from multiple select to the database. So a user can choose more than one products in a multiple select. I've tried the code like below but i got this error "ErrorException Array to string conversion".
Here is my blade.php
<div class="form-group row" style="display:none;" id="inputbarang">
<label class="col-form-label col-lg-3 col-sm-12">Barang</label>
<div class="col-lg-4 col-md-9 col-sm-12">
<select class="form-control m-select2" width="500px" id="kt_select2_1" name="id_product[]" multiple="multiple">
<option value=""></option>
#foreach($produk as $p)
<option value="{{ $p->id }}">{{ $p->product }}</option>
#endforeach
</select>
</div>
</div>
and here is my controller
$id_promo = Promo::select('id')
->where('delete', 0)->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')->first();
$id_product = [];
$id_product[] = $request->id_product;
// $id_products = $id_product['id_product'];
foreach ($id_product as $i) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $i,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}
Any helps will be appreciated, thank you so much
Try below code:
$id_promo = Promo::select('id')
->where('delete', 0)
->orderBy('created_at', 'DESC')
// ->take(1)
->pluck('id')
->first()
;
$id_products = $request->id_product;
foreach ($id_products as $id_product) {
DetailPromo::create([
'id_promo' => $id_promo,
'id_product' => $id_product,
'det_potongan' => $request->potongan,
'det_jumlah_potongan' => $request->jumlah_potongan
]);
}

Laravel - Form select categories from database

I have database tables 'Events' and 'Categories'.
I want to assign a category to an event using a select dropdown in the form. I also want to be able to edit it and update it. The code I have currently given me the following error -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'category_id' cannot be null
addEvent.blade.php
<div class="form-group">
<div class="form-group">
<div class="form-group">
{!! Form::Label('category_id', 'Category:') !!}
<select> class="form-control" name="category_id">
#foreach($categories as $category)
<option value='{{ $category->id}}'> {{ $category->category}}</option>
#endforeach
</select>
</div>
</div>
</div>
eventController
public function addEvent(Request $request)
{
$this->validate($request, [
'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required',
'time' => 'required',
'trip_id' => 'required',
]);
$start_date = Carbon::parse($request['start_date'])->format('Y-m-d');
$end_date = Carbon::parse($request['end_date'])->format('Y-m-d');
$tripCheck = Trip::where('id', $request['trip_id'])
->whereDate('startdate', '<=', $start_date)
->whereDate('enddate', '>=', $start_date)
->whereDate('startdate', '<=', $end_date)
->whereDate('enddate', '>=', $end_date)
->first();
if ($tripCheck) {
$events = new Events;
$trips = Trip::all();
$categories = Categories::pluck('category','id');
$events->category_id = $request['category_id'];
$events->colour = $request['colour'];
$events->event_name = $request['event_name'];
$events->start_date = $request['start_date'];
$events->end_date = $request['end_date'];
$events->time = $request['time'];
$events->address = $request['address'];
$events->notes = $request['notes'];
$events->trip_id = $request['trip_id'];
$events->save();
return redirect('trips')->with('success', 'The new event has been added to your trip')->with('trips', $trips)->withCategories($categories);
} else
{
return redirect('trips')->withErrors(['The dates you added are not within Trip start and end date.']);
}
public function display($id)
{
$categories = Categories::all();
return view('/addEvent')->with('trip_id', $id)->withCategories($categories);
}
editEvent
<div class="form-group"> Category:
<input type="select" name="category" class="form-control" value="{{$events->category}}" placeholder="Category" />
</div>
You are closing your <select> too early. Change
<select> class="form-control" name="category_id">
to
<select class="form-control" name="category_id">
to make it have a name, class etc

Laravel 5.3 select pluck method

Controller method:
public function edit($id){
$match2 = Match::pluck('team_a_id', 'id');
return view('admin.accept.edit', compact('match2'));
}
And view file:
{{ Form::select('matches_id', $match2, null, ['class' => 'form-control']) }}
And my table:
Table from model Match (table name: matches):
Table from model Team (table name: teams):
Table teams is connected (references) with table matches( team_a_id and team_b_id is connected with table teams). The select method with view returned me only ID with tables:
I need have team_name with table teams not id.
When I change method pluck:
$match2 = Match::pluck('id', 'id');
And view:
{{ Form::select('matches_id', Team::find($match2)->team_a_id." vs. ".Team::find($match2)->team_b_id, null, ['class' => 'form-control']) }}
Laravel returned error:
Invalid argument supplied for foreach() (View:
C:\xampp\htdocs\football\football\resources\views\admin\accept\edit.blade.php)
This is metohd edit so I must have highlighted record that was previously selected.
Ok I repair this. I write method:
public function edit($id){
$match = Match::select()->orderBy('updated_at', 'asc')->get();
$selectedMatch = DB::table('usermatches')->find($id)->matches_id;
return view('admin.accept.edit', compact('match', 'selectedMatch'));
}
And view:
<select name="matches_id" id="matches_id" class="form-control selectpicker" data-live-search="true" data-size="5">
<option value=0>Wybierz wydarzenie</option>
#foreach($match as $role)
<option value="{{ $role->id }}" {{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}>
{{ Team::find($role->team_a_id)->team_name }} vs. {{ Team::find($role->team_b_id)->team_name }} ({{$role->date}}; <?php echo date('G:i',strtotime($role->time)); ?> | Liga {{ League::find($role->league_id)->name }} | {{ Sport::find($role->sport_id)->name }})
</option>
#endforeach
</select>
In model view I compare id with two tables and it working ;)
{{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}

Laravel 5.3 Form Builder Assign 'value' Dynamically on Select Options

How do i assign the 'value' on the Laravel Form Builder Select Options dynamically in my views?
Example:
Function
public function create()
{
$categories = \DB::table('categories')->pluck('name', 'id');
return view('link.create')->with('categories', $categories);
}
View
<div class="form-group">
{!! Form::label('Link Category') !!}<br />
{!! Form::select('category',
(['0' => 'Select a Category'] + $categories),
null,
['class' => 'form-control']) !!}
</div>
Result
<select name="category" class="form-control">
<option value="0">Select a Category</option>
<option value="1">Laravel</option>
<option value="2">Zend Framework</option>
<option value="3">CakePHP</option>
<option value="4">PHP</option>
</select>
I would like the 'value' of the Select Options to be identical to the Option Content.
Like:
<option value="1">Laravel</option>
Should be like:
<option value="Laravel">Laravel</option>
If you pluck only the name, you can do something like this:
public function create()
{
$categories = \DB::table('categories')->pluck('name');
// creates ['Laravel' => 'Laravel', 'PHP' => 'PHP'...]
$categories = array_combine($categories, $categories);
return view('link.create')->with('categories', $categories);
}
You can just pluck name for both key and value
public function create()
{
$categories = \DB::table('categories')->pluck('name', 'name');
// Combine your default item
$categories = ['0' => 'Select a Category'] + collect($categories)->toArray();
return view('link.create')->with('categories', $categories);
}
Your view modified as below
<div class="form-group">
{!! Form::label('Link Category') !!}<br />
{!! Form::select('category', $categories, null, ['class' => 'form-control']) !!}
</div>

Categories