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
Related
I have a form that has a dropdown to select a staff member and a date from and date to field where they can pick their required dates and it should show all the selected staff member's records in that date range but it only shows all the records for that staff member, never in the required date range. This is what I have tried
Controller:
public function vehiclereport()
{
$startDate = '2021/01/01';
$endDate = '2021/12/12';
$energy = VehicleLog::join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')
->join('smsstaff', 'vehicleslog.smsstaff_key', '=', 'smsstaff.smsstaff_key')
->when(request()->input('smsstaff_key'), function ($query) {
$query->where('smsstaff.smsstaff_key', request()->input('smsstaff_key'));
})
->whereDate('log_dt', '>=', $startDate)
->whereDate('log_dt', '<=', $endDate)
->get();
$cars = Vehicle::get();
$staff = Staff::all();
return view('admin.vehiclereport', compact('energy', 'cars', 'staff', 'startDate', 'endDate'));
}
View:
<form>
<select name="smsstaff_key" id="smsstaff_key">
<option></option>
#foreach ($staff as $staffMember)
<option value="{{$staffMember->smsstaff_key}}" {{request()->input('smsstaff_key') === $staffMember->smsstaff_key ? 'selected="selected"' : ''}}>{{$staffMember->name}}</option>
#endforeach
<input type="date" class="form-control" name="startDate">
<input type="date" class="form-control" name="endDate">
</select>
<button>Filter by selected staff member</button>
</form>
There's a few issues here:
(a) You have your inputs inside the select, move them out of the select,
(b) you have the from/to dates in a bad format. They should look like YYYY-MM-DD,
(c) you aren't actually initialising the inputs with those dates i.e. doing something like <input type="date" name="startDate" value="{{ $startDate }}" /> and
(d) You aren't reading the dates from the input you currently have them static.
Try this code instead:
public function vehiclereport()
{
$startDate = request()->input('startDate', '2021-01-01');
$endDate = request()->input('endDate','2021-12-12');
$energy = VehicleLog::join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')
->join('smsstaff', 'vehicleslog.smsstaff_key', '=', 'smsstaff.smsstaff_key')
->when(request()->input('smsstaff_key'), function ($query) {
$query->where('smsstaff.smsstaff_key', request()->input('smsstaff_key'));
})
->whereDate('log_dt', '>=', $startDate)
->whereDate('log_dt', '<=', $endDate)
->get();
$cars = Vehicle::get();
$staff = Staff::all();
return view('admin.vehiclereport', compact('energy', 'cars', 'staff', 'startDate', 'endDate'));
}
and the view:
<form>
<select name="smsstaff_key" id="smsstaff_key">
<option></option>
#foreach ($staff as $staffMember)
<option value="{{$staffMember->smsstaff_key}}" {{request()->input('smsstaff_key') === $staffMember->smsstaff_key ? 'selected="selected"' : ''}}>{{$staffMember->name}}</option>
#endforeach
</select>
<input type="date" class="form-control" name="startDate" value="{{ $startDate }}">
<input type="date" class="form-control" name="endDate" value="{{ $endDate }}">
<button>Filter by selected staff member</button>
</form>
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
]);
}
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.
I have categories table and I want to display only the categories which are not available in the business_category table OR the business_category->approved is 2.
My code for that:
<div class="col-md-6">
<select multiple name="categories[]" id="categories" class="form-control #error('categories') is-invalid #enderror" autofocus required>
#foreach($categories as $category)
#foreach($business_categories as $business_category)
#if(($business_category->approved==2) || ($business_category->category_id != $category->id))
<option value="{{$category->id}}">{{$category->name}}</option>
#endif
#endforeach
#endforeach
</select>
</div>
My Code in Controller:
$business_categories = BusinessCategories::join('categories', 'categories.id', '=', 'category_id')
->where('business_id', $id)
->select('categories.name as name', 'approved', 'category_id')
->get();
$categories = Categories::where('parent_id', '0')->select('id', 'name')->get();
return view('admin.businesses.edit', with([
'business_categories' => $business_categories,
'categories' => $categories,
]));
But this code displays the categories which is applied or not applied multiple times.
First, you need a hasMany businessCategories relationship on Categories model:
public function businessCategories()
{
return $this->hasMany(BusinessCategories::class);
}
Your query
Categories::orWhereDoesntHave('businessCategories')
->orWhereHas('businessCategories', function($query) {
$query->where('approved', 2);
})->get();
You can find more eloquent relationship query information here
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>