Laravel 5.1 cant use #foreach on collection - php

This is data I have:
but with this blade template code:
<tbody>
#foreach ($orders as $order)
<tr>
<td>{{$order->id}}</td> //51 line
<td>{{$order->order->b_first_name}} {{$order->order->b_last_name}}</td>
<td>{{$order->order->r_first_name}} {{$order->order->r_last_name}}</td>
<td>£{{$order->total}}</td>
<td>{{$order->validity->diffForHumans()}}</td>
</tr>
#endforeach
</tbody>
I got this error:
ErrorException in fbe60fc17d23b35313269a941fc4d6f0 line 51: Trying to
get property of non-object (View:
/home/dgadmin/public_html/test/resources/views/admin/expired.blade.php)
What is the problem here? Why I cant use #foreach loop ?

First, go into your /storage/framework/views folder and look at line 51 for the file called fbe60fc17d23b35313269a941fc4d6f0. I see you said that it was $order->id, but I was not sure if you checked the compiled view that is actually served or admin/expired.blade.php. The compiled view is the one throwing the error, so the line number will correspond with the compiled view, not the blade you are making. When you look on this line you will see what is missing. This error is thrown because you are trying to access a null value on the model. If you want to go the lazy route, change your loop to this:
<tbody>
#foreach ($orders as $order)
<tr>
<td>{{isset($order->id)? $order->id: ''}}</td> //51 line
<td>{{isset($order->order->b_first_name)? $order->order->b_first_name : '' }} {{isset($order->order->b_last_name)? $order->order->b_last_name : ''}}</td>
<td>{{isset($order->order->r_first_name)? $order->order->r_first_name : ''}} {{isset($order->order->r_last_name)? $order->order->r_last_name : ''}}</td>
<td>£{{isset($order->total)?$order->total : ''}}</td>
<td>{{$order->validity->diffForHumans()}}</td>
</tr>
#endforeach
</tbody>
This will print the loop as expected, changing any missing values (like the one that triggered this errror) to a blank string.

Related

Getting weird undefined foreach error in Laravel Blade

I'm working with Laravel 5.8 and I have this syntax:
#php($counter_foreach = 0)
#foreach($memnames as $mem=>$memname)
#php
#endphp
#endforeach
Now when I run this, I get syntax error, unexpected 'endforeach' (T_ENDFOREACH) error:
But when I remove #php #endphp, and replace it with html, the error will be gone!
So what's going wrong here?
Is there anything wrong about using #php after #foreach in Laravel Blades?
Try to add #endphp everytime you add #php like this:
#php($counter_foreach = 0)
#endphp
#foreach($memnames as $mem=>$memname)
#php
#endphp
#endforeach
You actually do not need to make separate php variable for the iterations, so since you have a foreach loop already your logic should be something like this.
#foreach($this as $that) {
#if ($loop->first)
// some logic
#endif
#if ($loop->last)
// some logic
#endif
#endforeach
The $loop variable is available inside the foreach and you check for the iteration number you need inside, I just added some basic uses. Here is some more useful documentation.

Tryind to display json object into blade php laravel

i'm trying to display this json column into blade file
But i get Trying to get proprty 'en' of non object
<tr>
<th>Title en</th>
<th>Title ar</th>
<th>Description</th>
<th>Session Number</th>
<th>Session Per Week</th>
<th>Session Duration</th>
<th>Show</th>
</tr>
#foreach($model as $program)
<tr>
<th>{{json_decode($program->title)->en}}</th>
<th>{{json_decode($program->title)->ar}}</th>
<th>{{$program->description}}</th>
<th>{{$program->sessions_number}}</th>
<th>{{$program->sessions_per_week}}</th>
<th>{{$program->session_duration}}</th>
<th>{{$program->is_shown ? 'Yes' : 'No'}}</th>
</tr>
#endforeach
</thead>```
if your JSON format is something like
{"en":"title", "ar":"other-title"}
Then it should work.
My best guess is the en key doesn't exist on that title property.
If you are using the latest PHP then you can use the Nullsafe operator (?->) if not then use the isset check or use the null coalescing operator ??
<th>{{json_decode($program->title)->en ?? '' }}</th>
Also, be sure that $program->title itself is not null doing something like:
#php $title = isset($program->title) ? json_decode($program->title): null #endphp
<th>{{$title->en ?? '' }}</th>
But it is better to create a Accessor for this type of thing in the eloquent model. So you can directly do something like
$program->en_title;
So the blade file is clean and easy to understand but I don't suggest to go Accessor path if you are not reusing the code even if it makes the code cleaner. It is just my preference.
It looks like your title property is not an object, you should debug first to check it out, use dd() function to see inside this property
it appeared that my column was in trasnlatable array
and i just needed to call getTranslation mehtod and path to it the col and the app local jsu like that
{{getTranslation('title', 'en')}}

How To Call Procedure MySql in Laravel And Pass it to Blade.php

I got problem when i want to call procedure on MySql, this my code
$proc = DB::statement("call ambilKesimpulanLayak ('".$user->dosen->nip."')");
return view('dosen.data_saya',compact('proc'));
when i load data_saya.blade.php it's showing an error like this
Invalid argument supplied for foreach() (View:
E:\SKRIPSI\Skripsi_AHP\resources\views\dosen\data_saya.blade.php)
but i has suplied argument foreach on my blade.php
#foreach ($proc as $p)
<tr>
<td>{{$p->nama_jabatan}}</td>
<td>
{{$p->kesimpulan}}
</td>
</tr>
#endforeach
what's wrong with my code? , Sorry for my bad english..
Instead of DB::statement("call ambilKesimpulanLayak ('".$user->dosen->nip."')");
try DB::select(DB::raw("call ambilKesimpulanLayak ('".$user->dosen->nip."')"));
Hi Every one this case is has been solved by doing this. Go To database.php on config
after that search my SQl and Add this code below options =>
'options' => PDO::ATTR_EMULATE_PREPARES => true

Call to helper function from blade template in outside controller results in 'class not found'

I am doing a proof-of-concept/toy example to try and familiarize myself with the ins and outs of Laravel and I ended up running into an error that I wasn't expecting.
Within my blade template, I made a call to a helper function contained within the controller (controller was generated via php artisan make:controller CBookController). And the call from within the blade template was {{isset($val->prep) ? CBookController::toDate($val->prep) : ''}}. I got it working and all was dandy. I decided that I wanted to pull that helper function out of that controller so that I could use it elsewhere in the project.
NOTE: I could only call the code from within the view if I included the line:
<?php use app\Http\Controllers\CBookController; ?> within the blade template
Mind you, this all worked properly and didn't throw any errors.
So here is where it started to get funky.
I made the call >php artisan make:controller Helper
I refactored all of the references in the view to say Helper instead of CBookController i.e.
{{isset($val->prep) ? CBookController::toDate($val->prep) : ''}} --> {{isset($val->prep) ? Helper::toDate($val->prep) : ''}}
and
<?php use app\Http\Controllers\CBookController; ?> --> <?php use app\Http\Controllers\Helper; ?>
before I refactored everything, it all worked properly. But after said refactoring, things started to get all screwy.
Please note: I do realize that for a more advanced laravel user, making a "helper" controller doesn't make sense. Again, as a more novice user, I was just trying to make small incremental changes that would still work as expected.
I am not trying to figure out the proper way to use helper functions (at least at this junction), nor figure out anything else other than, why would creating a new controller and then referencing that controller within the view give me guff.
My intuition is telling me that the make:controller is doing more behind the scenes than I am aware of and that is what is causing the issue, but I do not know what to look for or where to look.
Any explanation on why this small change breaks the page would be helpful
I can confirm that both the CBookController.php and the Helper.php are in the same directory, so there shouldn't be a filepath issue with the use statement in the view.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CBookController extends Controller
{
public function main()
{
$result = \DB::connection('database')
->table("docs")
->join("plans","docs.bn","=","plans.bn")
->select('docs.bn',
"plans.a",
'b as Status',
'c as fee',
'd as exec',
'e as mail',
'f as prep')
->where('id','=','19')
->where('b','=','N')
->get()
->toArray();
return view('test.Control_Book_Test')->with('result',$result);
}
public static function toDate($strToConvert)
{
return date("m-d-Y",strtotime($strToConvert));
}
}
this is the original controller (edited column fields for anonymity, I believe everything was kept consistent, but regardless, it did work before hand)
The new controller is as follows
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Helper extends Controller
{
public static function toDate($strToConvert)
{
return date("m-d-Y",strtotime($strToConvert));
}
}
and finally, here is the view (before refactoring)
<?php use app\Http\Controllers\CBookController; ?>
#section('content')
<div style = "overflow-x: scroll">
<table class="table table-striped- table-bordered table-hover table-checkable" id="magicWand">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3/th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
<th>Col 7n</th>
<th>Col 8</th>
<th>Col 9</th>
<th>Col 10</th>
<th>Col 11</th>
<th>Col 12</th>
<th>Col 13</th>
<th>Col 14<br></th>
</tr>
</thead>
<tbody>
#foreach($result as $k => $val)
<tr>
<td>{{isset($val->bn) ? $val->bn : ''}}</td>
<td>{{isset($val->ShortPlanName) ? $val->ShortPlanName : ''}}</td>
<td>n/a</td>
<td>{{isset($val->Status) ? $val->Status : ''}}</td>
<td>{{isset($val->fee) ? "$".number_format($val->fee,2) : ''}}</td>
<td>{{isset($val->exec) ? CBookController::toDate($val->exec) : ''}}</td>
<td>{{isset($val->mail) ? CBookController::toDate($val->mail) : ''}}</td>
<td>{{isset($val->prep) ? CBookController::toDate($val->prep) : ''}}</td>
<td>n/a</td>
<td>n/a</td>
<td>n/a</td>
<td>n/a</td>
<td>n/a</td>
<td>n/a</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
For brevity's sake, there's no point in repasting the entire file with just some refactored names, but here are the lines that contain the refactored reference
<?php use app\Http\Controllers\CBookController; ?> (very first line)
<td>{{isset($val->exec) ? CBookController::toDate($val->exec) : ''}}</td> (within the #foreach)
<td>{{isset($val->mail) ? CBookController::toDate($val->exec) : ''}}</td> (within the #foreach)
<td>{{isset($val->prep) ? CBookController::toDate($val->exec) : ''}}</td> (within the #foreach)
I expected the page to work just fine, but I end up getting the an error page with the message "Class 'app\Http\Controllers\Helper' not found"
What you can do is create a custom facade, for your custom function.
Create a folder in App/Http/Custom
Create a class DateHelper
Add Your Function to the class
Use the custom facade in your view using the #inject
usage
#inject('helper', 'App\http\DateHelper');
{{ $helper->toDate('params') }};

Trying to get property of non-object - retrieve set of data in laravel 5.0

I'm having this issue with laravel when I'm getting data from two tables.This is my query. It exists in a controller.
$switches = DB::table('sw_pairs')->
join('cust_sw_pair','cust_sw_pair.sw_pair_id', '=', 'sw_pairs.sw_pair_id')->
select(
DB::raw(
'cust_sw_pair.sw_pair_id,
count(cust_sw_pair.sw_pair_id) as totcount,
pri_sw, sec_sw,
count(if(pri_sw_admin_status="Admin Down" AND sec_sw_admin_status="Admin Down", 1, NULL)) as downCount')
)->
groupBy('cust_sw_pair.sw_pair_id')->get();
When I execute this query I get this error.
"Trying to get property of non-object"
but the above query is succesfully returning the first row of the result set when I used first() instead of the get() method.
This is the retrieving part which exists on the view:
#foreach($switches as $switch_pair)
<tr>
<td>{{$switches->pri_sw}} / {{$switches->sec_sw}}</td>
<td><span>{{$switches->downCount}},{{$switches->totcount}</span></td>
<td><i class="fa fa-level-up"></i> 40% </td>
<td>{{$switches->downCount}} / {{$switches->totcount}}</td></tr>
#endforeach
How can I successfully get all the results?
There are two problems with your code:
a) you are looping through $switches but are not using the single items within the loops
b) missing accolade in the second td
So to give you the result of the above fixed:
#foreach($switches as $switch_pair)
<tr>
<td>{{ $switch_pair->pri_sw }} / {{ $switch_pair->sec_sw }}</td>
<td><span>{{ $switch_pair->downCount }},{{ $switch_pair->totcount }}</span></td>
<td><i class="fa fa-level-up"></i> 40% </td>
<td>{{ $switch_pair->downCount }} / {{ $switch_pair->totcount }}</td></tr>
#endforeach

Categories