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

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

Related

How to Store Multiple Select Values in Laravel 8?

So my problem is that if i try to save only one value like "Location in the layout" of a post it works, but the moment i am saving an array I'm getting something like ["value 1" , "value 2"] in the DB, therefore it cant be read and in the CRUD-Controller there is no data saved when i am editing.everything works perfectly except the value i am getting from the data. I would appreciate any help, methods or alternatives
edit.blade.php
<div class="form-group">
<label>Select Post Location</label>
<select
class="form-control select2 select2-hidden-accessible"
multiple=""
data-placeholder="Select Locations"
style="width: 100%"
tabindex="-1"
aria-hidden="true"
name="post_locations[]"
id="post_locations"
>
<option value="TopBox-GR" #if ($post->post_locations == "TopBox-GR") selected #endif>TopBox-GR</option>
<option value="TopBox-C3" #if ($post->post_locations == "TopBox-C3") selected #endif>TopBox-C3</option>
<option value="TopBox-C4" #if ($post->post_locations == "TopBox-C4") selected #endif>TopBox-C4</option>
</select>
</div>
home controller
public function index()
{
$posts = post::where([['status',1], ['post_locations','TopBox-GR']])->get();
return view('user.blog',compact('posts'));
}
and view:
<div class="topbox-c4">
#foreach ($posts as $post)
<a href="{{ route('post',$post->slug) }}">
<div class="image-topbox-c4-container">
<img src="{{ Storage::disk('local')->url($post->image)}}" />
</div>
<div class="text-topbox-c4-container">
<h3>{{$post->title}}</h3>
<p>
{{$post->subtitle}}
</p>
</div>
</a>
#endforeach
</div>
post.controller:
public function update(Request $request, $id)
{
$this->validate($request,[
'title'=>'required',
'subtitle'=>'required',
'slug'=>'required',
'body'=>'required',
'image'=>'required',
'post_locations'=>'required',
]);
if($request->hasFile('image'))
{
$imageName = $request->image->store('public');
}
$post = post::find($id);
$post->image = $imageName;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->post_locations = $request->post_locations;
$post->body = $request->body;
$post->status = $request->status;
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
$post->save();
return redirect(route('post.index'));
}
Firstly you should get selected locations in $selectLocations variable and all locations in $allLocations variable for edit.blade.php
In edit.blade.php, you can display like this:-
#foreach($selectLocations as $value)
<select class="form-control" name="post_locations[]" multiple=''>
<option value="">Select Location</option>
#foreach($allLocations as $val)
<option #if($value['id'] == $val->id) {{ 'selected' }} #endif value="{{ $val->id }}">{{ $val->name}}</option>
#endforeach
</select>
#endforeach

search with pagination is not working in laravel

I make it in 1 route with
in route
Route::get('/all-students', 'AdminController#studentList')->name('admin.student');
Route::post('/all-students', 'AdminController#searchByClassRoll')->name('search-by-class-roll');
in controller funtion student list
public function studentList(Request $request)
{
Session::put('url.intended2', URL::current());
Session::put('url.intended', URL::previous());
if (isset($request->class)) {
if (isset($request->roll)) {
if ($request->class == 'all') {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->orderBy('id', 'DESC')
->paginate(20);
} else {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
} else {
if ($request->class == 'all') {
return redirect()->route('admin.student');
} else {
$students = DB::table('students')
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
}
} else {
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
}
return view('admin.student-list')->with('students', $students);
}
post method
public function searchByClassRoll(Request $request)
{
$class = $request->class;
$roll = $request->roll;
if (isset($request->class)) {
if (isset($request->roll)) {
return redirect()->route('admin.student', ['class' => $class, 'roll' => $roll]);
} else {
return redirect()->route('admin.student', ['class' => $class]);
}
}
}
in blade
#if(method_exists($students,'links'))
{!! $students->links() !!}
#endif
normally when I click page 2 it returns
all-students?page=2
when I search something all-students?class=2 and then i click on pagination page it returns again all-students?page=2 and remove the search data from URL.
form from view
<form action="{{ route('search-by-class-roll') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="type" value="student_list">
<div class="row gutters-8">
<div class="col-4-xxxl col-xl-4 col-lg-3 col-12 form-group">
<div class="ui-alart-box">
<div class="default-alart">
<div class="result" role="alert">
#if(app('request')->input('class') || app('request')->input('roll'))
See All<span> | </span>
#endif
Showing results {{$students->count()}} of {{$students->total()}} entries
</div>
</div>
</div>
</div>
<div class="col-3-xxxl col-xl-3 col-lg-3 col-12 form-group">
<input type="number" name="roll" placeholder="Search by Roll..." class="form-control">
</div>
<div class="col-4-xxxl col-xl-3 col-lg-3 col-12 form-group">
<select class="select2 form-control" name="class" required>
<option value="all">All Classes</option>
<option value="baby">baby</option>
<option value="nursery">nursery</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
</div>
<div class="col-1-xxxl col-xl-2 col-lg-3 col-12 form-group">
<button type="submit" class="fw-btn-fill btn-gradient-yellow">SEARCH</button>
</div>
</div>
</form>
i want to made this because I want this in 1 URL just because if someone manually entered the URL with search data he can see the output. but in here I can't get the result with pagination from blade. when I turned into page 2 it remove the search variable from URL. and paginate the whole data. how can I get result with pagination after search?
There is the simpler way
Just add with your paginated array.
{{ $users->withQueryString()->links() }}
Coming directly to your controller. You don't need any other route or method you can handle this filtering on same route and in same method.
public function studentList(Request $request)
{
if(!empty($request)){
$query = $request->all();
$students = DB::table('students')->orderBy('id', 'DESC');
if(isset($request->class) AND $request->class != '' AND $request->class != 'all')
$students = $students->where('class', '=', $request->class);
if(isset($request->roll) AND $request->roll != '')
$students = $students->where('roll', '=', $request->roll);
$students = $students->paginate(20);
return view('admin.student-list', compact('students','query'));
}
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
return view('admin.student-list', compact('students'));
}
Change few things in your view
<form action="{{ route('admin.student') }}" method="get"> change route and method to get
{{ csrf_field() }} //remove this
Below your table inside view write this code. The appends() is most important otherwise pagination in your filtered data won't work.
#if(isset($query))
{{ $students->appends($query)->links() }}
#else
{{ $students->links() }}
#endif
Try use append on paginator blade
{{$students->appends(\Illuminate\Support\Facades\Input::except('page'))->links()}}

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

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.

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.1 - Store input data in my session

I have a view show.php of my single product, when user click on ADD PRODUCT my controller CartController.php update my session cart and update my cartSession table,
Now i'm tryng to put new data (Color input,Size input, Quantity input) on my session and also in my CartSession table. But i dont know why it doesn't work.
-I think that the principal problem is that $request->get('input') doesn't pass to my CartController.php , i tried to return
$request->all() and there is not nothing.
CartController.php
namespace dixard\Http\Controllers;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\CartSession;
use dixard\CartItem;
use dixard\Shipping;
use Session;
// i think that all classes are ok
public function add(Product $product, CartSession $CartSession,Request $request)
{
$id = $request->get('id');
$cart = \Session::get('cart');
$product->quantity = $request->get('qty');
$product->size = $request->get('size');
$product->color = $request->get('color');
$cart[$product->id] = $product;
\Session::put('cart', $cart);
return $request->all(); // here i tried to get all inputs but it shows me nothing result
$subtotal = 0;
foreach($cart as $producto){
$subtotal += $producto->quantity * $producto->price;
}
$session_code = Session::getId();
$CartSession = new CartSession();
$session_exist = CartSession::where('session_code', $session_code)->orderBy('id', 'desc')->first();
if (isset($session_exist)) {
$s = new CartSession;
$data = array(
'subtotal' => $subtotal,
);
$s->where('session_code', '=', $session_code)->update($data);
}else {
$CartSession = new CartSession();
$CartSession->session_code = $session_code;
$CartSession->subtotal = $subtotal;
$CartSession->save();
}
//return $cart;
//salveremo tutte le informazioni nel array cart nella posizione slug
foreach($cart as $producto){
$this->saveCartItem($producto, $CartSession->id, $session_code, $cart);
}
return redirect()->route('cart-show');
}
Routes.php
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('cart/add/{product}', [
'as' => 'cart-add',
'uses' => 'CartController#add'
]);
show.php view
Get Data about the product is ok, title, description, color avaible, price ecc. all information pass to my view.
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="{{$product->id}}">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="p_color">Colore</label>
<select name="color" id="p_size" class="form-control">
#foreach($colors as $color)
<option value="{{ $color->color }}">{{ $color->color }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="size">Size</label>
<select name="size" id="p_size" class="form-control">
<option value="XS">XS</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="qty">Quantity</label>
<select name="qty" id="p_qty" class="form-control">
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
</select>
</div>
</div>
</div>
<div class="product-list-actions">
<span class="product-price">
<span class="amount">{{$product->price}}</span>
<input type="submit" class="btn btn-lg btn-primary" >
ADD PRODUCT
</input>
</div><!-- /.product-list-actions -->
{!! Form::close() !!}
Thank you for your help!
You have to explicitly set the post-method to be "get" or you need to change your router to accept the request as post. Even though you're calling the route by name, Form::open defaults to "POST"
https://laravelcollective.com/docs/5.2/html#opening-a-form
Option 1. Change
Route::get('cart/add/{product}',...
to
Route::post('cart/add/{product}',...
Option 2. Change
{!! Form::open(['route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}
to
{!! Form::open(['method'=>'GET', 'route'=> ['cart-add', $product->id],'class'=>'form-horizontal form-label-left'])!!}

Categories