simply this code is my get data solution, this models are relationships and my result is true but i can't get data from relationship and show that on view, for example;
$data = UserAccountNumber::with(['currency_type'])->orderBy('id', 'DESC')->paginate(50);
this code return below result:
LengthAwarePaginator {#585 ▼
#total: 2
#lastPage: 1
#items: Collection {#601 ▼
#items: array:2 [▼
0 => UserAccountNumber {#588 ▶}
1 => UserAccountNumber {#589 ▼
#table: "user_account_numbers"
#guarded: array:1 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:9 [▼
"id" => 2
"user_id" => 17
"account_number" => "24234234"
"card_number" => "242423423"
"sheba" => "asdasdad"
"currency_type" => 5
"status" => 0
"created_at" => "2016-05-13 10:55:00"
"updated_at" => "2016-05-13 10:55:00"
]
#original: array:9 [▶]
#relations: array:1 [▼
"currency_type" => CurrencyType {#603 ▼
#table: "currency_type"
#fillable: array:3 [▶]
#dates: array:1 [▶]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:7 [▼
"id" => 5
"user_id" => 1
"currency_type" => "EURO"
"currency_symbol" => "EUR"
"created_at" => "2016-04-17 12:07:47"
"updated_at" => "2016-04-17 12:07:47"
"deleted_at" => null
]
View:
in view i can get UserAccountNumber data, but i can not get currency_type and show that on view:
<table class='table-style' cellpadding='0' cellspacing='0'>
#foreach ($data as $key=>$contents)
<tr>
<td>{{$contents->card_number}}</td>
<td>{{$contents->card_number}}</td>
<td>{{$contents->seba}}</td>
<td>{{$contents->created_at}}</td>
<td>
{{$contents->currency_type->currency_type}}
</td>
</tr>
#endforeach
</table>
i get error for {{$contents->currency_type->currency_type}} on view.
Error:
Trying to get property of non-object
POST UPDATED:
class UserAccountNumber extends Model
{
protected $table = 'user_account_numbers';
protected $guarded = ['id'];
public function user()
{
return $this->belongsTo('App\Http\Models\User');
}
public function currency_type()
{
return $this->belongsTo('App\Http\Models\CurrencyType', 'currency_type', 'id');
}
}
First thing to improve is in your UserAccountNumber model. Your currency_type relation should be written like:
public function currencyType()
{
return $this->belongsTo(CurrencyType::class, 'currency_type', 'id');
}
Your call would then look like:
// using the currencyType() method from above
$data = UserAccountNumber::with('currencyType')
->orderBy('id', 'DESC')
->paginate(50);
You then can access the currency type in your with with:
#foreach ($data as $key=>$contents)
$contents->currencyType->currency_type
#endforeach
It seems some of the UserAccountNumber do not have currency_type attached to it. Add something like this to your code:
#if (isset($contents->currency_type))
{{ $contents->currency_type->currency_type }}
#endif
Or:
{{ $contents->currency_type->currency_type or 'There is not type' }}
Related
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.
Do you know why the " #if ($nextRegistration->participants->registration_type->contains('certificate_available', 'Y')) [ " shows "Property [registrationType] does not exist on this collection instance"?
I want to show for each registration a link "Get certificate" if the column "certificate_available" of the "registration_types" table has the value "Y".
<ul class="list-group">
#foreach($nextRegistrations as $nextRegistration)
#if(!empty($nextRegistration->conference) || !empty($nextRegistration->conference->start_date))
#if ($nextRegistration->participants->registration_type->contains('certificate_available', 'Y'))
<a href="{{route('conferences.certificateInfo',
[
'regID'=> $nextRegistration->id])}}"
class="btn btn-primary ml-2">Download certificate</a>
#endif
</li>
#endif
#endforeach
</ul>
The participant model has the registration_type():
class Participant extends Model
{
public function registration(){
return $this->belongsTo('App\Registration');
}
public function registration_type(){
return $this->belongsTo('App\RegistrationType');
}
}
To get the $nextRegistrations the code is:
$nextRegistrations = $user->registrations()
->with('participants.registration_type')
->whereHas(
'conference',
function ($query) {
$query->where('end_date', '>', now());
}
)->paginate($pageLimit);
And $nextRegistrations shows like:
LengthAwarePaginator {#336 ▼
#total: 3
#lastPage: 1
#items: Collection {#320 ▼
#items: array:3 [▼
0 => Registration {#308 ▼
...
#relations: array:1 [▼
"participants" => Collection {#327 ▼
#items: array:1 [▼
0 => Participant {#332 ▼
...
#relations: array:1 [▼
"registration_type" => RegistrationType {#337 ▼
#fillable: array:7 [▶]
....
#attributes: array:10 [▼
"id" => 1
"name" => "general"
"description" => "desc general"
"conference_id" => 1
"certificate_id" => 1
"certificate_available" => "Y"
]
...
}
]
...
}
]
}
]
...
}
1 => Registration {#321 ▶}
2 => Registration {#317 ▶}
]
}
....
}
How do you retrieve the data from the database. You may need to use the with method:
$data = Participant::with('registration_type')->get()
or in the view use "registration_type" as a method, not as a property:
$nextRegistration->participants->registration_type()
You can find more about the belongs to relationship here: https://laravel.com/docs/5.6/eloquent-relationships#one-to-many-inverse
this is my model where i set my relation
public function user() {
return $this->hasOne('App\Client','id','client_id');
}
and here the controller
i have two relations here my invoice product realtion works fine and well but $clients shows 2 rows in view
$clients = Invoice::with('user')->get();
$invoice_id = $invoice->id;
$invoices = Invoice::with('products')->where('id', '=', $invoice_id)->firstOrFail();
return view('admin.invoices.show', compact('invoice','invoices'),compact('clients'));
and the view
#foreach($clients as $client)
<td>{{ $client->user->title ?? 'بدون مشتری' }}</td>
#endforeach
now when i visit my view i get 2 td tags with the same value of the client name (title) any idea what i have done wrong ?
and here is the dd of the
#observables: []
#relations: array:1 [▼
"user" => Client {#769 ▼
#fillable: array:14 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:17 [▼
"id" => 1
"title" => "مشتری اول"
"description" => "مشتری اول"
"fax" => 123
"adrress1" => "مشتری اول"
"adrress2" => null
"adrress3" => null
"adrress4" => null
"adrress5" => null
"telephone1" => 123
"telephone2" => null
"telephone3" => null
"telephone4" => null
"telephone5" => null
"client_type" => null
"created_at" => null
"updated_at" => null
the problem was i was looping through all the relations that would possibly happen for that model so i just did a simple filter which was a were clause for my relation and the set the id of invoice for that to bring just the attributes i need and that more efficient as i see in the documentation
$clients = Invoice::with('user')->where('id','=',$invoice_id)->get();
**** UPDATE *******************************************************
I'm not sure why, but moving everything into the controllers index() method rather than having it in the show() method solved the problem. Don't know why it works, but it does.
Original Question:
Cant figure out what is wrong here, i have followed the docs, tried variations, etc... still no luck making this work correctly.
Model A: (Slide)
public function carousels() {
return $this->belongsToMany(Carousel::class)->withTimestamp()
}
Model B: (Carousel)
public function slides() {
return $this->belongsToMany(Slide::class)->withTimestamp()
}
Pivot Table
--------------------------------------------------
|carousel_id | slide_id | created_at | updated_at|
--------------------------------------------------
From Controller:
public function show(Carosuel $carousels) {
$carousels = $carousel->with('slides)->get();
return view('myView', compact(['carousels']));
}
In the following dump, the "slides" are not in the attributes object of the collection; however, they are in the relations object. Im not sure if this is normal behavior or if the slides array should be in the attributes object. If the latter is the case, then how does one go about making that happen?
$caousels dump:
Collection {#1320 ▼
#items: array:20 [▼
0 => Carousel {#798 ▼
#fillable: array:4 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 1
"name" => "Prof. Andre Gerlach"
"category" => "Dr."
"active" => 0
"deleted_at" => null
"created_at" => "2018-04-07 21:10:52"
"updated_at" => "2018-04-07 21:10:52"
]
#original: array:7 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"slides" => Collection {#1300 ▼
#items: array:5 [▼
0 => Slide {#1023 ▶}
1 => Slide {#1024 ▶}
2 => Slide {#1025 ▶}
3 => Slide {#1026 ▶}
4 => Slide {#1027 ▶}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => Carousel {#799 ▶}
2 => Carousel {#800 ▶}
In the View:
foreach($carousels as $carousel){
echo $carousel->name;
foreach($carousel->slides as $slide){
echo $slide->tag;
}
}
This throws the E_ERROR Invalid argument supplied for foreach() in view
If, however, I cast this to an array, it works. Problem is that i also need to paginate the results. Once i do, the slides array is again inaccessible.
public function show(Carosuel $carousels) {
// This works - slides are available to me in the view
$carousels = $carousel->with('slides)->get()->toarray();
// This DOESN'T work - slides are not available to me in the view
$carousels = $carousel->with('slides)->paginate(6)->toarray();
return view('myView', compact(['carousels']));
}
dump as array:
array:12 [▼
"current_page" => 1
"data" => array:6 [▼
0 => array:8 [▼
"id" => 1
"name" => "Prof. Andre Gerlach"
"category" => "Dr."
"active" => 0
"deleted_at" => null
"created_at" => "Apr 07 2018"
"updated_at" => "2018-04-07 21:10:52"
"slides" => array:5 [▼
0 => array:11 [▶]
1 => array:11 [▶]
2 => array:11 [▶]
3 => array:11 [▶]
4 => array:11 [▶]
]
]
1 => array:8 [▶]
2 => array:8 [▶]
3 => array:8 [▶]
4 => array:8 [▶]
5 => array:8 [▶]
]
"first_page_url" => "//localhost:3000/admin/carousel/show?page=1"
"from" => 1
"last_page" => 4
"last_page_url" => "//localhost:3000/admin/carousel/show?page=4"
"next_page_url" => "//localhost:3000/admin/carousel/show?page=2"
"path" => "//localhost:3000/admin/carousel/show"
"per_page" => 6
"prev_page_url" => null
"to" => 6
"total" => 20
The problem here is that, in the view, the slides key is no longer accessible. Throws following error (only if I use ->paginate()).
E_ERROR Trying to get property 'slides' of non-object
Everything I have read in the docs and from other sources show this to be a pretty basic operation. For the live of me, i cant figure out why its causing such an issue. I should be able to access this in the view by simply nesting a foreach.
Any help with this would be greatly appreciated.
In the following dump, the "slides" are not in the attributes object of the collection; however, they are in the relations object.
Yes this is normal.
This is where you have a problem:
public function show(Carosuel $carousels) {
// ...
return view('myView', compact(['carousels']));
}
Typehinting a model in a function is reserved for model binding. Which is not what you're doing here since you don't have an {id} or some other parameter in your route.
Remove the typehinting and call the model instead:
public function show() {
$carousels = Carousel::with('slides')->get();
return view('myView', compact(['carousels']));
}
If you'd like to remove the dependency from the method, you should do it in the constructor instead.
Edit:
While I don't see any other problem and the above solution should work, if it's true that ->toArray() works for you (but you still need pagination), you could just convert the underlying collection:
public function show() {
$carousels = Carousel::with('slides')->paginate();
$carousels->setCollection(collect($carousels->getCollection()->toArray()));
return view('myView', compact(['carousels']));
}
Can you try this?
Model B: (Carousel)
public function slides() {
return $this->hasMany(Slide::class)->withTimestamp();
}
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