Im building a laravel app
#foreach ($reviews as $review)
<div>
#if ($review->child_id == null)
... display data
#else
{{$review->child_id}}
#while ($review->child_id) // this line throws error
...display data
#php
//trying to instantiate variable again
$review = App\Review::where('id',$review->child_id); // this line doesnt work
#endphp
#endwhile
#endif
</div>
#endforeach
Basically I cant access the $review->child_id property it throws this error
Undefined property: Illuminate\Database\Eloquent\Builder::$child_id (View: /var/www/html/projects/guest-book/resources/views/reviews/comment.blade.php) (View: /var/www/html/projects/guest-book/resources/views/reviews/comment.blade.php)
but if I var dump it is there and I used it in previous if statement and it works just fine there.
What I am trying to do is display comment section each comment has child and parent ids.
If comment does not have child id it is displayed normally otherwise it is indented.
How can I re-instantiate the variable in blade and how come I cant access that property which was used before in the same blade?
dd($review) :
Review {#248 ▼
#fillable: array:6 [▶]
#dates: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:11 [▼
"id" => 4
"grav_url" => "https://www.gravatar.com/avatar/25d755d39ba840f931b70f90cbd591eb?d=https%3A%2F%2Fwww.gravatar.com%2Favatar%2F&s=20"
"full_name" => "user name"
"review" => "answer"
"ip_address" => "127.0.0.1"
"deleted_at" => null
"parent_id" => "0"
"child_id" => "5"
"user_id" => null
"created_at" => "2018-01-29 14:09:16"
"updated_at" => "2018-01-29 14:09:16"
]
#original: array:11 [▶]
#changes: []
#casts: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
#forceDeleting: false
}
dd($reviews) all reviews are basically like the one above so I didnt open them.
LengthAwarePaginator {#242 ▼
#total: 4
#lastPage: 1
#items: Collection {#244 ▼
#items: array:4 [▼
0 => Review {#245 ▶}
1 => Review {#246 ▶}
2 => Review {#247 ▶}
3 => Review {#248 ▶}
]
}
#perPage: 12
#currentPage: 1
#path: "http://localhost:8000"
#query: []
#fragment: null
#pageName: "page"
}
Controller index method :
public function show() {
$reviews = Review::
where('deleted_at', NULL)
->where('parent_id', 0)
->paginate(12);
return view('reviews.reviews', compact('reviews'));
}
Check review is empty or not-
#else
#while ($review!=null&&$review->child_id!=null)
...display data
#php
//trying to instantiate variable again
$review = App\Review::where('id',$review->child_id)->first();
#endphp
#endwhile
#endif
If you are using laravel 5.5, then you can use optional() helper method-
#while (optional($review)->child_id)
You need to check child_id more explicitly
#foreach ($reviews as $review)
<div>
#if ($review->child_id == null)
... display data
#else
{{$review->child_id}}
#while (optional($review)->child_id) // change the if
...display data
#php
//trying to instantiate variable again
$review = App\Review::where('id',$review->child_id)->first(); //add first
#endphp
#endwhile
#endif
</div>
#endforeach
Related
I am using Eloquent ORM with a many to many (n to n) relationship between users(players) and rooms(sessions), where users are attached to a room. They are able to play cards (scrum) in order to value an software issue through their card estimation.
When I load my view, which uses an optional {{id?}} parameter, it looks into my DB::Class and finds the room through the parameter.
The problem is, when I want to access the id attribute of my attached user to display the received information in my view. Although my debug shows, that I receive the correct data, I get the error mentioned above.
My View:
"cards.blade.php"
<h1 align="center"><u>Userid</u> {{$currentUser->id}}</h1>
<h1 align="center"><u>Username:</u> {{$currentUser->name}}</h1>
<h1 align="center"><u>Your estimation is:</u> {{$currentUser->userValue}}</h1>
<h1 align="center">Last updated: {{$currentRoom->updated_at->diffForHumans() ?? ''}}</h1>
<h1 align="center">#if ($currentUser->isAdmin === 0 || null )
'You are sadly not an admin'
#else 'You are an admin'
#endif</h1>
<h1 align="center">Room Number: {{$currentRoom->id}}</h1>
"SessionController.php#getPlayerInfo"
public function getPlayerInfo($id)
{
$currentRoom = Session::findOrFail($id);
$currentUser = $currentRoom->users;
$tmp = $currentUser->id;
dd($currentUser);
return view('sessions.cards')
->with('currentUser', $currentUser)
->with('currentRoom', $currentRoom);
}
"web.php"
Route::get('play/{id?}', 'SessionController#getPlayerInfo')
->name('sessions.cards')
->middleware('auth');
dd($currentUser) output:
Collection {#305 ▼
#items: array:1 [▼
0 => User {#302 ▼
#fillable: array:3 [▶]
#hidden: array:2 [▶]
#casts: array:1 [▶]
#connection: "mysql"
#table: "users"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 1
"name" => "admin"
"email" => "admin#email.com"
"email_verified_at" => null
"password" => "$2y$10$AhpAyD2NR2TW.kBYOMzTAe1kfRh73CtMhRxaGH0Bi2OrhPcSA65f."
"userValue" => null
"isAdmin" => null
"remember_token" => null
"created_at" => "2019-11-13 10:13:20"
"updated_at" => "2019-11-13 10:13:20"
]
#original: array:12 [▶]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#rememberTokenName: "remember_token"
}
]
}
As the dd implies, your $currentUser contains a collection, so it's not a single record. You have to loop through its content to get a single user. Something like this:
#foreach ($currentUser as $user)
{{ $user->id }}
#endforeach
It's a collection.Use foreach like
#foreach($curretUser as $cuser)
<h1 align="center"><u>Userid</u> {{$cuser->id}}</h1>
<h1 align="center"><u>Username:</u> {{$cuser->name}}</h1>
<h1 align="center"><u>Your estimation is:</u> {{$cuser->userValue}}</h1>
<h1 align="center">Last updated: {{$currentRoom->updated_at->diffForHumans() ?? ''}}</h1>
<h1 align="center">#if ($cuser->isAdmin === 0 || null )
'You are sadly not an admin'
#else 'You are an admin'
#endif</h1>
<h1 align="center">Room Number: {{$currentRoom->id}}</h1>
#endforeach
There are many tables. One characterizes the sliders, the other contains information inside these sliders. My task is to transfer all values from tables into one template. That is, when choosing the desired slider from the possible, we were given relevant information.
What has been done:
Tables were connected by a one-to-many method.
Main model
class AdminSlider extends Model
{
public function aboutUs()
{
return $this->hasMany('App\AboutUs');
}
public function mainSlider()
{
return $this->hasMany('App\MainSlider');
}
}
Dependent models looks like
class MainSlider extends Model
{
public function adminSlider()
{
return $this->belongsTo('App\AdminSlider', 'slider_id', 'id');
}
}
2. Was created the variable which is working with template in controller
public function index()
{
$adminSlidersItems = $this->getSliderInfo();
$sliderInfo = view('admin.adminEditText')->with('sliderInfo',$adminSlidersItems)->render();
$this->vars = array_add($this->vars, 'sliderInfo', $sliderInfo);
return $this->renderOutput();
}
public function getSliderInfo() {
$sliderInfoItems = $this->as_rep->get();
return $sliderInfoItems;
}
When I looked into variable admin in controller I saw Collection
{#230 ▼
#items: array:6 [▼
0 => AdminSlider {#231 ▼
#connection: "mysql"
#table: "admin_sliders"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 1
"title" => "Main Slider"
"path" => "http://jinol/admin/sliders/mainslider"
"img" => "mainslider.jpg"
"alias" => "mainslider"
"created_at" => null
"updated_at" => null
]
#original: array:7 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
1 => AdminSlider {#232 ▶}
2 => AdminSlider {#233 ▶}
3 => AdminSlider {#234 ▶}
4 => AdminSlider {#235 ▶}
5 => AdminSlider {#236 ▶}
]
}
template.layout
#extends('admin.site')
#section('admin.adminNavigation')
{!! $adminNavigation !!}
#endsection
#section('admin.adminEditText')
{!! $sliderInfo !!}
#endsection
Define our variables in template.
#if(count ($sliderInfo) > 0) <br>
<div id="content-page" class="content group"><br>
#foreach($sliderInfo as $info)<br>
<tr><br>
<td class="align-left">{{$info->adminSlider->id}}</td><br>
</tr><br>
#endforeach<br>
</div><br>
#endif
In the end of this I have got an error.
Trying to get property 'id' of non-object (View:
W:\domains\jinol\resources\views\admin\adminEditText.blade.php).
How can I find my mistake?
try
$info->adminSlider['id']
insted of
$info->adminSlider->id
i think it will be solve your problem
In your controller change:
public function index()
{
$adminSlidersItems = $this->getSliderInfo();
$sliderInfo = view('admin.adminEditText')->with('sliderInfo',$adminSlidersItems)->render();
$this->vars = array_add($this->vars, 'sliderInfo', $sliderInfo);
return $this->renderOutput();
}
To:
public function index()
{
$adminSlidersItems = $this->getSliderInfo();
return view('admin.adminEditText', ['sliderInfo' => $adminSlidersItems]);
}
In your view change
<td class="align-left">{{$info->adminSlider->id}}</td><br>
To
<td class="align-left">{{optional($info->adminSlider)->id}}</td><br>
Apparently, not all of your $sliderInfo's have a ->adminSlider defined and you get an error when trying to access id on it when it's set to null. The optional helper will only try to access the id when ->adminSlider is not null.
I know this question has been asked and answered multiple times but none of the previous post answers my question.
I'm running a website with Laravel 5.2 on an Linux server and get the error :
Trying to get property of non-object (View: /mnt/nfs/preprod/greement/htdocs/resources/views/qual_ops/qual_ops_show.blade.php)
It works perfectly well with a certain user with WampServer but doesn't on the server (with the same user). Some users also get the error because they are missing a parameter, I'm aware of that.
I checked the databases and files but the only difference is that the tables need to have a capital letter at the beginning of their names (changes made before so the website can run on the server.
Controller - UserQualOpsController.php :
public function show($id)
{
$compte = Compte::find($id);
$userQualOps = User_qual_ops::join('qual_ops', 'qual_ops.id_qual_ops', '=', 'user_qual_ops.id_qual_ops')
->join('type_qual_ops', 'type_qual_ops.id_type_qual_ops', '=', 'qual_ops.id_type_qual_ops')
->where('id_compte', $id)
->orderBy('type_qual_ops.nom', 'asc')
->orderBy('qual_ops.code_qual_ops', 'asc')
->orderBy('date_obtention', 'desc')
->get();
$params = [];
foreach($userQualOps as $userQualOp){
$params[$userQualOp->id_qual_ops] = Qual_ops_param::where(function($query){
$query->where('id_organisme', 1)
->orWhere('id_organisme', Auth::user()->id_organisme);
})
->where('id_qual_ops', $userQualOp->id_qual_ops)
->first();
}
return view('qual_ops/qual_ops_show', [ 'compte' => $compte,
'userQualOps' => $userQualOps,
'params' => $params]);
}
View - qual_ops_show.blade.php:
#foreach($params as $param)
ERROR HERE -> #if($param->id_qual_ops == $userQualOps[$i]->id_qual_ops)
<?php
$obtentionDate = Carbon::parse($userQualOps[$i]->date_obtention);
switch($param->premier_seuil_unite){
case 'jour(s)':
$echDatePrem = $obtentionDate->addDay($param->premier_seuil);
break;
case 'mois':
$echDatePrem = $obtentionDate->addMonth($param->premier_seuil);
break;
}
$obtentionDate = Carbon::parse($userQualOps[$i]->date_obtention);
switch($param->deuxieme_seuil_unite){
case 'jour(s)':
$echDateDeux = $obtentionDate->addDay($param->deuxieme_seuil);
break;
case 'mois':
$echDateDeux = $obtentionDate->addMonth($param->deuxieme_seuil);
break;
}
if($echDatePrem->max(Carbon::now()) == $echDatePrem)
$alertNumber = 0;
elseif($echDateDeux->max(Carbon::now()) == $echDateDeux)
$alertNumber = 1;
else
$alertNumber = 2;
?>
#if($alertNumber == 2)
<td class="col-md-2">{{Carbon::parse($userQualOps[$i]->date_obtention)->format('d/m/Y')}}<span class="glyphicon glyphicon-alert red-glyphicon float-right"></span></td>
#elseif($alertNumber == 1)
<td class="col-md-2">{{Carbon::parse($userQualOps[$i]->date_obtention)->format('d/m/Y')}}<span class="glyphicon glyphicon-alert orange-glyphicon float-right"></span></td>
#elseif($alertNumber == 0)
<td class="col-md-2">{{Carbon::parse($userQualOps[$i]->date_obtention)->format('d/m/Y')}}<span class="glyphicon glyphicon-ok green-glyphicon float-right"></span></td>
#endif
#endif
#endforeach
dd($params) :
array:16 [▼
4 => Qual_ops_param {#592 ▼
#table: "Qual_ops_param"
#primaryKey: "id_qual_ops_param"
#fillable: array:5 [▶]
+timestamps: false
#connection: null
#perPage: 15
+incrementing: true
#attributes: array:8 [▶]
#original: array:8 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
5 => Qual_ops_param {#586 ▶}
6 => Qual_ops_param {#411 ▶}
7 => Qual_ops_param {#407 ▶}
22 => Qual_ops_param {#589 ▶}
1 => Qual_ops_param {#412 ▶}
2 => Qual_ops_param {#585 ▶}
8 => Qual_ops_param {#581 ▶}
9 => Qual_ops_param {#580 ▶}
10 => Qual_ops_param {#578 ▶}
11 => Qual_ops_param {#591 ▶}
12 => Qual_ops_param {#576 ▶}
13 => Qual_ops_param {#584 ▶}
17 => Qual_ops_param {#574 ▶}
18 => Qual_ops_param {#573 ▶}
3 => Qual_ops_param {#590 ▶}
]
dd($userQualOps) :
Collection {#593 ▼
#items: array:179 [▼
0 => User_qual_ops {#594 ▼
#table: "User_qual_ops"
#primaryKey: "id_user_qual_ops"
#fillable: array:5 [ …5]
+timestamps: false
#connection: null
#perPage: 15
+incrementing: true
#attributes: array:10 [ …10]
#original: array:10 [ …10]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [ …1]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
1 => User_qual_ops {#595 ▶}
2 => User_qual_ops {#596 ▶}
.
.
.
I'm just trying to understand why does it work on WampServer (because $params is definitely an array) and how to get this thing working on the Linux server.
I can't run the composer/phpartisan on the server and have to work without it.
I got a slight issue,for some reason I'm unable to access my attributes from a relationship model.
I keep getting the same error, 'Undefined property: Illuminate\Database\Eloquent\Collection::$season'
I have been staring at this all day and I couldn't find a solution for it.
<?php namespace App\Http\Controllers;
use App\Show;
use App\Episode;
class TestController extends Controller {
public function test(){
$shows = Show::where('active',1)->get();
foreach ($shows as $show) {
if($show->active == 1 && $show->airday == date('N'))
{
echo 'test';
$episode = $show->episodes()->orderBy('id', 'desc')->take(1)->get();
\Debugbar::info($episode);
//this is the line where he gives me
echo('New episodes avaible, Season '.$episode->season.' Episode '.$episode->episode.' From '.$show->name);
//end error
}
}
}
}
?>
Although if I do a print out of the $episode variable I can clearly see the properties I wish to access.
Illuminate\Database\Eloquent\Collection {#150
#items: array:1 [
0 => App\Episode {#241
#table: "episodes"
+timestamps: true
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#original: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
At the moment I'm clueless whats wrong with the code.
I hope someone can point me in the right direction.
When you call ->take(1)->get() you're telling Eloquent (the builder, really) to give you back a Collection object with 1 item in it.
So when you're trying to access your $season property, you're actually trying to access it on a Collection object and not the Model that you think.
You can do a couple of things:
You can replace your ->take(1)->get() call with ->first(),
or you can treat your current $episode variable as a collection, and retrieve the actual episode you care about by accessing $episode[0],
or you can call first on your current $episode variable ($episode = $episode->first()) to get the first model object within it.
I'm new to Laravel and I cannot figure out how to get the value of an item from within the returned collection. Here is my code:
$aircraft = Aircraft::join('pams_shared.shared_aircraft', 'aircraft.shared_aircraft_id', '=', 'pams_shared.shared_aircraft.shared_aircraft_id')
->select('aircraft.*', 'shared_aircraft.*')
->where('aircraft.owner_id',Auth::user()->owner_id)
->where('registration',$reg)
->get();
I want to get the value from aircraft.aircraft_id but that's where I get stuck. I've tried:
$id = $aircraft->aircraft_id;
I've tried:
$id = $aircraft->aircraft.aircraft_id;
I've also tried:
$id = array_get($aircraft, 'aircraft_id');
But I'm getting null as a value. When I perform either a var_dump($aircraft) or dd($aircraft) I'm able to confirm that the data is there.
In my view I am able to access the value by looping through, but I need this data in my controller to perform a second query on another table.
Hope that makes sense. Cheers.
EDIT
When running dd($aircraft); I get this:
Collection {#239 ▼
#items: array:1 [▼
0 => Aircraft {#240 ▼
#fillable: array:8 [▶]
#table: "aircraft"
#primaryKey: "aircraft_id"
#connection: null
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:16 [▼
"aircraft_id" => 5
"owner_id" => 2
"shared_aircraft_id" => 67443
"year" => 2012
"serial_number" => "C127RG3"
"registration" => "C-SMTH"
"created_by" => 2
"modified_by" => 2
"created_at" => "0000-00-00 00:00:00"
"updated_at" => "0000-00-00 00:00:00"
"aircraft_code" => "2072438"
"aircraft_mfr" => "CESSNA"
"aircraft_model" => "172RG"
"aircraft_type" => 4
"aircraft_eng" => 1
"aircraft_cat" => 1
]
#original: array:16 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]
}
When you use get() method on a query builder it would return an array no matter how many record it gets. So you can access it by pointing it by index. By the way do not forget to check for emptiness to overcome possible errors.
$id = 0;
$aircraft = Aircraft::join('pams_shared.shared_aircraft', 'aircraft.shared_aircraft_id', '=', 'pams_shared.shared_aircraft.shared_aircraft_id')
->select('aircraft.*', 'shared_aircraft.*')
->where('aircraft.owner_id',Auth::user()->owner_id)
->where('registration',$reg)
->get();
// now you can access properties
if(count($aircraft) > 0) $id = $aircraft[0]->aircraft_id;
If you execute the query with get() you will always get a collection as result. Even if you just need one model. The simplest way to change that is to use first():
$aircraft = Aircraft::join('pams_shared.shared_aircraft', 'aircraft.shared_aircraft_id', '=', 'pams_shared.shared_aircraft.shared_aircraft_id')
->select('aircraft.*', 'shared_aircraft.*')
->where('aircraft.owner_id',Auth::user()->owner_id)
->where('registration',$reg)
->first();
$id = $aircraft->aircraft_id;