laravel - null value in foreach - php

i would like to know how to solve this problem. Im making a query with a "whereIn" clause (In this case, its named "Price") in which there is a "<=" operator. But im getting an error which indicates that one variable is null. Im using laravel 5.4.
code used so far:
controller:
function catalog(Request $abc) {
$categoryesc = $abc->categoryesc;
$manufaesc = $abc->manufaesc;
$priceesc = $abc->priceesc;
$modelesc = $abc->modelesc;
if (empty($modelesc)) {
$robots = DB::table('robots')->whereIn('Category_id', [$categoryesc])->whereIn('Manufacturer_id', [$manufaesc])->whereIn('Price', '<=', $priceesc)->get();
}elseif (Auth::check()){
$robots = DB::table('robots')->where('Model', $modelesc)->first();
$colours = DB::table('colours')->pluck('Colour', 'id');
}
else {
return redirect('login');
}
return view('catalog', compact('robots', 'categories', 'colours'));
}
blade file:
#if (empty($_GET['modelesc']))
<h1>Catalog</h1>
{{ Form::open(array('method' => 'GET')) }}
{{ Form::select('categoryesc', ['3,2,1' => 'Any Category', '1' => 'Light', '2' => 'Medium', '3' => 'Heavy'], '3,2,1') }}
{{ Form::select('manufaesc', ['2,1' => 'Any Make', '1' => 'Xenon', '2' => 'Tauron'], '2,1') }}
{{ Form::select('priceesc', ['1000000' => 'Any Price', '100' => '100', '200' => '200'], '1000000') }}
{{ Form::submit('Search') }}
{{ Form::close() }}
<div>Available models</div>
<b>On this page ({{ $robots->count() }} robots)</b>
<div id="area1">
#foreach($robots as $robot)
{{ Form::open(array('method' => 'GET')) }}
{{ Form::hidden('modelesc', $robot->Model) }}
{{ Form::submit($robot->Model) }}
{{ Form::close() }}
#endforeach
</div>
#else
<h1>Orders</h1>
<button> < </button>
{{ Form::open(['method' => 'POST']) }}
{{ Form::hidden('users_id', Auth::user()->id) }}
Model: {{ Form::text('Model', $robots->Model) }}<br><br>
{{ Form::hidden('Category_id', $robots->Category_id) }}
{{ Form::hidden('Fabrication_date', date('Y-m-d')) }}
Choose colour: {{ Form::select('Colour_id', $colours) }}<br><br>
{{ Form::hidden('Order_status_id', '1') }}
{{ Form::submit('Order') }}
{{ Form::close() }}
#endif
In the builder.php i previously added the "<=" operator to the function "invalidOperatorAndValue" at page 615 (in order for it to work). This is the error message:
ErrorException in Builder.php line 766:
Invalid argument supplied for foreach()
in Builder.php line 766
at HandleExceptions->handleError(2, 'Invalid argument supplied for
foreach()',
'C:\\Users\\Joao_Carvalho\\Laravel\\MegaRobot\\
vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php',
766, array('column' => 'Price', 'values' => '<=', 'boolean' => null, 'not'
=> false, 'type' => 'In')) in Builder.php line 766
at Builder->whereIn('Price', '<=', null) in CentralController.php line 26

Your whereIn for the condition on Price should be a where instead. whereIn is not the appropriate method for when you want to do a comparison with <=:
DB::table('robots')
->whereIn('Category_id', [$categoryesc])
->whereIn('Manufacturer_id', [$manufaesc])
->where('Price', '<=', $priceesc)
->get();
whereIn on the other hand should be used for testing whether a value is in an array, which is what you do in the two other cases.

WhereIn expects array as a second parameter as it is structured to check if field value is within the array.
whereIn('Price', '<=', $priceesc) will not work as second parameter is string and internally its expecting array and doing foreach on it.
You need to replace it with :
where('Price', '<=', $priceesc)

First, there is the whereIn issue addressed by the other answers.
However, in addition to that, the actual issue you're running into is that $robots is being set to two different things depending on the result of your if statements.
Inside if (empty($modelesc)), $robots is being set to a Collection of stdClass objects. When you foreach this result, you will loop through the Collection.
However, inside the elseif (Auth::check()), $robots is being set to an individual stdClass instance (you have used the first() method). When you foreach this result, you'll be looping through the properties on that one instance, which is not what you intended. One of the properties on this instance is null, which is what you are seeing.
A quick solution would be to wrap this result in a new collection:
$robots = collect([DB::table('robots')->where('Model', $modelesc)->first()]);

Related

Retrieve old value from Laravel Form::select

I have the following form field in a Laravel project in my create view (create.blade.php):
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), null, ['class' => 'form-control format']) }}
I retrieve this inside the format column in my database so i can use this data in my project.
Now, inside the edit (edit.blade.php) view I want to have the already selected data to reflect. So when the user has selected "video", the select option will already be set to Video.
While I was typing this question, i figured it out. Already typed the entire question so might as well post it to help someone out.
The third argument needs to correspond with the data I retrieve from the database. So, for example, if i wanted the Video to be selected, it would look like this:
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), 'is_video', ['class' => 'form-control format']) }}
I replaced the is_video with the variable that contains the data from my database and it's working as expected.
{{ Form::label('format', 'Type', ['class'=>'label']) }}
{{ Form::select('format', array('is_html' => "HTML", 'is_video' => 'Video'), $var->format, ['class' => 'form-control format']) }}

php combine variables into array for twig

so I have some php variables, some are form an array. I can print them like this
echo $arr->title;
echo $arr->date;
echo $xml;
echo $cover;
I am using twig. I think I need to combine specific php variables into one array(say book) so I can render my twig template with
echo $template->render(['book' => $book]);
then in my twig template be able to use
{{ title }}
{{ date }}
{{ xml }}
{{ cover }}
any tips on how to achieve this would be greatly appreciated .
Just create the array for your needs:
$viewData = [
'book' => [
'title' => $arr->title,
'date' => $arr->date,
'xml' => $xml,
'cover' => $cover,
]
];
echo $template->render($viewData);
Template
{{ book.title }}
{{ book.date }}
{{ book.xml }}
{{ book.cover }}
If you want to be able to use the data in your twig template like this:
{{ title }}
{{ date }}
{{ xml }}
{{ cover }}
then you need to pass on the data to the view like that:
echo $template->render([
'title' => $arr->title,
'date' => $arr->date,
'xml' => $xml,
'cover' => $cover,
]);

Laravel not letting me add styles to my Form::text()

This is my code for the form builder, and when I remove the array from the text() everything is fine, but when I add it I get this error
ErrorException in helpers.php line 454: htmlentities() expects
parameter 1 to be string, array given (View:
/Users/samir/Sites/elicant/resources/views/pages/classes.blade.php)
{!! Form::open(array("url" => 'addClass', "method" => 'post')) !!}
{!! Form::text('classname', array('style' => 'width:80%;')) !!}
{!! Form::text('classcolour') !!}
{!! Form::submit("Add") !!}
{!! Form::close() !!}
What have I done wrong?
Form::text has 3 parameters: $name, $value, array $options = array()
So to make your code working:
{!! Form::text('classname', null, array('style' => 'width:80%;')) !!}

Laravel PHP: Keep the chosen dropdown option stay selected on View

I have a homepage that contains a dropdown menu that allows the user to select a category and will display results depending on which option is chosen from the dropdown menu.
It is currently working fine in updating and displaying the correct results but now I've run into a minor issue where I want the dropdown to stay selected on the chosen category. Normally I would put a simple line of code within my view such as
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', array('option1' => 'Option1', 'option2' => 'Option2'), $video->category) }}
where $video is the model used in the controller.
However this situation is a little bit different because I need to pass the 'category' variable from within my controller so that the dropdown menu will stay on the selected category after the user makes their choice.
Controller:
public function index()
{
$vdo = Video::query();
$pic = Picture::query();
if($category = Input::get('category')){
$vdo->where('category', $category);
$pic->where('category', $category);
}
$allvids = $vdo->paginate(10);
$allpics = $pic->paginate(10);
$data = compact('allvids','allpics');
$this->layout->content = \View::make('home.pics_vids_overview',$data)->with('category', Input::get('category'));
}
View:
{{Form::open(array('route' => 'overview_select', 'files' => true)) }}
<div class="form-group">
{{ Form::label('category', 'Category:') }}
{{ Form::select('category', array('Category1' => 'Category1', 'Category2' => 'Category2', 'Category3' => 'Category3', 'Category4' => 'Category4'), array('class' => 'form-control')) }}
I've tried several approaches in passing the chosen 'category' variable back to the dropdown so that it will stay on the chosen option after the user makes their choice but none of them have worked for me yet. Any help is greatly appreciated!
You may try this:
{{
Form::select(
'category',
array('Category1' => 'Category1', 'Category2' => 'Category2'),
(isset($category) ? $category : 'Category1'),
array('class' => 'form-control')
)
}}
Use Form::model instead of Form::open to bind the model to the form and it will automatically pick up any values in the model:
{{ Form::model(array('route' => 'overview_select', 'files' => true)) }}

Symfony2 TimeType Field separate hour's and minute's input fields

I want to get two input fields for hours and minutes with the TimeType field.
I also want to set for the input field of time and hour an unique label, placeholder and / or input values. I also want to render each inpult field individually in TWIG, like
{{ form_row(form.TimeExtern[####HOUR FIELD####]) }}
{{ form_row(form.TimeExtern[####MINUTES FIELD####]) }}
My current code:
$builder->add('TimeExtern', 'time', array(
'input' => 'timestamp',
'widget' => 'single_text',
'required' => true,
'label' => 'Externe Zeit',
'attr' => array(
'help_text' => 'Zeitformat: Stunden:Minuten',
'input_group' => array(
'append' => '.icon-time',
)
),
));
This gives me ONE input field for hour and minutes together.
I've already read the docs but couldn't find a solution.
Any ideas?
The form_div_layout.html.twig renders the time widget using
{{ form_widget(form.hour, vars) }}
{% if with_minutes %}:{{ form_widget(form.minute, vars) }}{% endif %}
{% if with_seconds %}:{{ form_widget(form.second, vars) }}{% endif %}
So as far as I can see you would be able to use
{{ form_widget(form.TimeExtern.hour) }}
{{ form_widget(form.TimeExtern.minute)) }}
And then just add your details (label, placeholder, etc) in the attributes hash like
{{ form_widget(form.TimeExtern.hour, {'label': '', 'attr': {'placeholder': '' }}) }}
{{ form_widget(form.TimeExtern.minute, {'label': '', 'attr': {'placeholder': '' }}) }}

Categories