Laravel Multi-select the right way - php

I'm having trouble getting a Form Request to find a multi select input with Laravel. My request input always appears to be NULL. Is there anything I'm missing or wrong with my Syntax?
I've seen some examples mention dot notation syntax for multi selects in Laravel?
e.g.
$name = $request->input('products.0.name');
$names = $request->input('products.*.name');
But I'm assuming this is for multi dimensional selects?
I'm passing my request through to a Repository for data action
<select id="team" name="team[]" class="team" multiple>
#foreach ( $teams as $team )
<option value="{{ $team->id }}">{{ $team->name }}</option>
#endforeach
</select>
use Illuminate\Support\Facades\Input;
public function createUser( CreateUserRequest $request ){
$array = DB::transaction(function($request) use ($request)
{
$name = $request->input('name');
$email =$request->input('email');
// $team = $request->input('team[].*');
$s = $request->input('team');
$t =$request->get('team');
var_dump($s);//NULL
var_dump($t);//NULL
die();

Please check it may be working.
$name = $request->input('name');
$email =$request->input('email');
// array field
$team = $request->input('team');
foreach($team as $key=>$value){
$data->name = $name;
$data->email = $email;
// array value
$data->item = $value;
// save in datatabase
$data->save();
}

Related

Enum field filtration in Laravel

I need to add a drop-down menu that filtrates with enum values from the table. Instead of that it gets the values from the rows. Any and all help gratefully received.
This is what I have managed to get so far.
View:
<div>
<span>
<select class="mb-2">
<option value="Status" disabled selected>Status</option>
#foreach ($status_filter as $key => $status)
<option value="{{ $key }}">
{{$status}}
</option>
#endforeach
</select>
</span>
</div>
Controller:
$status_filter = Competition::pluck('status');
$request->flash();
return view('competition.index', compact('competitions', 'status_filter'));
This is what I need to get from the migration:
$table->enum('status',['inactive','to_push','active'])->default('inactive');
You can grab those enum values from the table. But there is no direct way. You have to use laravel query builder using raw.
$statusValues = DB::select(DB::raw("SHOW COLUMNS FROM competitions WHERE Field = 'status' "))[0]->Type;
$matches = array();
preg_match('/^enum\((.*)\)$/', $statusValues, $matches);
$enumValues = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enumValues = $v;
}
print_r($enumValues)
If i got it right you want to make a filter for status like listing all active ou inactive. I think the easiest way to do this is add a query on your variable $status_filter on the controller. Something like: $status_filter = Competition::where('status', 'active')->pluck('status');
As #SazzadHussain suggested adding this block of code inside my model class solved the issue.
public static function getPossibleEnumValues($table, $column) {
$type = DB::select(DB::raw("SHOW COLUMNS FROM $table WHERE Field = '{$column}'"))[0]->Type ;
preg_match('/^enum\((.*)\)$/', $type, $matches);
$enum = array();
foreach( explode(',', $matches[1]) as $value )
{
$v = trim( $value, "'" );
$enum = Arr::add($enum, $v, $v);
}
return $enum;
}
After that getting it from my Controller like that:
$enumoption = Competition::getPossibleEnumValues('competitions','status');

how to foreach data from same database with two tables laravel

I have written a code to view data but I'm having some problems.
From the code, I wrote it's viewing the data from one table which is the $details. But I also wanna view the data from the $detailsAns.
How can I do that? also, can I foreach two data from that two tables?
my code below:
public function queries($companyID, $entityType, $entityValue)
{
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach($details as $key => $detailsValue)
{
if(!array_key_exists($detailsValue->intent, $data))
{
$data[$detailsValue->intent] = [];
}
if(!array_key_exists($detailsValue->reply, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['answer'][$detailsValue->reply] = $detailsValue->id;
}
if(!array_key_exists($detailsValue->queries, $data[$detailsValue->intent]))
{
$data[$detailsValue->intent]['question'][$detailsValue->queries] = $detailsValue->id;
}
}
ksort($data);
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
}
so as you can see I can return the data from foreach for $details but now I want to return data for $detailsAns also. how can I do that?
my database structure:
table1:
table2:
so to get the data it first has to select the company id, eType, eVal, and intent so from that now i need to display the reply and queries.
The output that i want is as below:
So as you can see i can output the questions table in the foreach that i did. and if i change the foreach to $detailsAns then i display the reply.. but i want to view the both now
It isn't very clear from the data provided how the tables relate to each other. If the answer has the same id value as the question, it is easy to relate them by structuring the arrays so that they are keyed by the common value.
$data = [];
$details = DiraQuestion::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($details AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['question'][$datum->id] = $datum->queries;
}
$detailsAns = DiraResponses::where('company_id', $companyID)->where('eType', $entityType)->where('eVal', $entityValue)->get();
foreach ($detailsAns AS $datum) {
if (!isset($data[$datum->intent])) $data[$datum->intent] = ['question' => [], 'answer' => []];
$data[$datum->intent]['answer'][$datum->id] = $datum->reply;
}
At this point, since you said that there is no relation between the data sets, just pass the data array to the view the way you already are:
return view('AltHr.Chatbot.queries', compact('data','entityType','entityValue','companyID'));
And loop through both elements of data, printing out values in the view:
#foreach ($data['approval-document']['question'] as $id=>$question)
<p>Question #{{ $id }}: {{ $question }}</p>
#endforeach
#foreach ($data['approval-document']['answer'] as $id=>$answer)
<p>Answer #{{ $id }}: {{ $answer }}</p>
#endforeach

populate array from database inside foreach loop and fetch it later

I want to populate an array with ids that are fetched from db table. Later I want to fetch those ids from the array to insert into another db table. Below is the code:
public function storeBaritems()
{
$id = Auth::user()->id;
$bartypearray = array();
$bartypes = request('select1'); // <select id="select1" name="select1[]"
foreach ($bartypes as $type) {
$bartypearray[] = Bartype::select('bartype_id')
->where('bar_type_name','like',$type)
->where('restaurant_id', $id)
->get();
}
$baritems = request('itemname'); //<input type="text" class="hookah-field" name="itemname[]">
$descriptions = request('description'); //<input type="text" class="hookah-field" name="description[]">
$quantity = request('quantity'); //<input type="text" class="hookah-field" name="quantity[]">
$prices = request('price'); //<input type="text" class="hookah-field" name="price[]">
$i = 0;
foreach ($bartypearray as $item) {
Bar_menu::create([
'item_name'=>$baritems[$i],
'description'=>$descriptions[$i],
'quantity'=>$quantity[$i],
'price'=>$prices[$i],
'res_id'=>$id,
'type_id'=>$item->bartype_id
]);
$i += 1;
}
}
The HTML form dynamically creates new fields with same "name" attribute. Right now, I am getting the error - "Exception in Collection.php line 1527:
Property [bartype_id] does not exist on this collection instance." Any solution would help. Thanks
You could use the pluck method.
$bartypearray = Bartype::where('bar_type_name','like',$type)
->where('restaurant_id', $id)
->pluck('bartype_id');
With this method there is no need for the first foreach.
BTW. I would highly recommend to loo into all collection methods

How to assign a value to an associative array

I have an associative array called $data and a function called sendToView() which is accepting $email and $vehicleid as parameters. I need to assign those parameters to $data array. How can I do that?
Here I have mentioned what I have tried but it is giving "Trying to get property of non-object" error. How can i solve that?
public function sendToView($email, $vehicleid) {
$data['details'] = array(
'email' => $email,
'id' => $vehicleid
);
$this->load->view('pages/OfferView',$data);
}
offerView.php
<?php foreach ($details as $detail) {?>
<form name="myform4" action="<?php echo base_url(). 'OfferCtrl/sendEmailToReview/'. $detail->email .'/'. $detail->id ;?> " method="POST">
I have done this in offerView.php.Is that error occurs due to this?
When you just pass an data array can access it through foreach loop like this
$email = $data['details']['email'];
$id = $data['details']['id'];
public function sendToView($email, $vehicleid) {
$data['details'] = array();
$data['details']['email'] = $email;
$data['details']['id'] = $vehicleid;
$this->load->view('pages/OfferView',$data); //load it into the view
}
when accessing it, you can loop through and push your data back to a variable
i.e
$email = $details['email'];
$id = $details['id'];
You can then proceed to use the variables $email and $id in your code .
Something like this:
<form name="myform4" action="<?php echo base_url(). 'OfferCtrl/sendEmailToReview/'. $email .'/'. $>id ;?> " method="POST">

Laravel dropdown without optgroup

I decided to try out Laravel and wanted to create dropdowns for my form. I created a convinience method inside my BaseController that I use to get the data from the database. Below is the function listing:
protected function getList( $model, array $fields, $empty = 'Select option below' )
{
$options = array();
$owner = strtolower( $model ) . 's';
$records = $model::lists($fields[1], $fields[0]);
if( !empty( $records ) ){
foreach( $records as $key => $value ){
$options[$owner][$value] = $key;
}
}
$options[$owner][''] = $empty;
return $options;
}
And then in the controller you can just use it like:
//Get groups
$groups = $this->getList( 'Group', array(
'name', 'id'
));
//Get Project Managers
$project_managers = $this->getList( 'ProjectManager', array(
'name', 'id'
));
The output of the select form control has an optgroup that references the owner of the list or the model rather. How can I remove the optgroup such that its not part of the contents of the dropdown?
Below is the output of the form:
<div class="input select">
<label for="project_manager">Project Manager</label>
<select name="project_manager_id">
<optgroup label="projectmanagers">
<option value="1">Riyaadh</option>
<option value="2">Luyanda</option>
<option selected="selected" value="">Select option below</option>
</optgroup>
</select>
</div>
You are adding another level within your getLists method with this line; $options[$owner][$value] = $key;, this is what is adding your optgroup, to get rid of this change the line to $options[$value] = $key;.
Optionally you can reduce the code of your getLists function to the following;
protected function getList( $model, array $fields, $empty = 'Select option below' )
{
$options = array();
$owner = strtolower( $model ) . 's';
$records = $model::lists($fields[1], $fields[0]);
if( !empty( $records ) ){
$options = array_flip($records);
}
$options[''] = $empty;
return $options;
}
This uses the array_flip method, which exchanges the keys as values and values as keys.
Try this...
$SchoolDetails = GeneralSettingModel::lists('SchoolName', 'id');
or
$SchoolDetails = DB::table('tablename')->lists('SchoolName', 'id');
{{ Form::select('SchoolName',array(''=>'Select School')+$SchoolDetails,null, array('id'=> 'SchoolName'))}}
Output:
<select id="SchoolName" name="SchoolName">
<option value="" selected="selected">Select School</option>
<option value="1">test</option>
<option value="2">test355wrew</option>
<option value="3">GOVT</option>
<option value="4">Kumaraguru</option>
<option value="5">valavan</option>
</select>
you can remove using JQuery by adding ID to select
$(function () {
$("#mySelect").children().remove("optgroup");
});
As Matt Burrow suggested it turned out that I was creating a multi-dimentional array which is translated to a list with optgroup.
I modified my function to rather exclude the owner which the records belong to. Below is my perfectly working function (excerpt):
...
if( !empty( $records ) ){
foreach( $records as $key => $value ){
$options[$value] = $key;
}
}
$options[''] = $empty;
...

Categories