How to set null if relations doesn't exist? - laravel

In Model I have:
public function publisher()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
In template blade I try to show data User:
#foreach($announcement->offers as $key => $item)
<img src="{{url($item->publisher->photo)}}">
#endforeach
The Problem is that if there is no data in the User table, the program crashes because I can not get the property $item->publisher->photo.
How to fix it?

You can do something like this:
#if (empty($item->publisher))
It's empty
#else
<img src="{{ url($item->publisher->photo) }}">
#endif

Working on memory here, but you could use #forelse/ #empty. These directives can be used if the object your'e iterating over is empty:
#forelse($announcement->offers as $key => $item)
<img src="{{url($item->publisher->photo)}}">
#empty
//default image or message?
#endforelse
https://laravel.com/docs/5.4/blade#loops

Related

How to iterate nested data in laravel blade view?

I have below the draft implementation. The spec is to show the parent information and children-grandchildren information.
#foreach ($parent as $children)
<x-icons.chevron-right>
<h1>{{ $parent->name }}</h1>
#if($person->has('children'))
// go back at the top for nested for each
#endif
#endforeach
One solution that you may recommend is to create an iterative function. But my problem for that, it does not completely render my component-icon chevron-right.
#php
function showHTML($person) {
$html = '';
foreach($person as $children) {
$html .= `
<x-icons.chevron-right>
<h1>$person->name</h1>
`;
if ($person->has('children')) {
$html .= showHTML($person->children);
}
}
return $html;
}
#endphp
{!! showHTML($person) !!}
Just wondering if you guys have other solution for this to show nested with a component icon? I would appreciate any answer.
I encountered the same thing, and it did not take me long to figure out that we can re-iterate a component.
In my case, I just created a root component and re-iterated it if it had children.
So I don't need to loop it any longer.
So my usage would like this below:
<x-parent person="$person"></x-parent>
And my root component parent.blade.php. So If there is person has children I just re-iterate the component and pass his children as a prop:
#props(['person'])
<x-icons.chevron-right>
<h1>{{ $person->name }}</h1>
#if($person->has('children'))
<x-parent person="$person->children"></x-parent>
#endif
You can try => value on your foreach, that will fetch data array value from backend.
Or can you show your code on backend (controller), that can easy to help you
#foreach ($parent as $children => $value)
<x-icons.chevron-right>
<h1>{{ $parent->name }}</h1>
<h3>{{ $value->data }}<h3>
#endforeach

foreach() argument must be of type array | object, null given (Laravel Livewire)

This code is working fine
public function render(){
$this->products = ProductModel::get();
return view('livewire.product');
}
But when I am trying to paginate using laravel livewire, it gives me an error
public function render(){
return view('livewire.product', [
'products' => ProductModel::paginate(10)
]);
}
Blade File
#foreach ($products as $product)
{{ $product->name }}
{{ $product->price }}
#endforeach
#if(!empty($products))
{{ $products->links() }}
#endif
import this in Component
use Livewire\WithPagination;
class Product extends Component
{
use WithPagination;
....
}
and add in view
#if(!empty($products))
{{ $products->links() }}
#endif
Ohh I got it.Actually I have already use $products variable as a global variable
and when I change $products to other name it works.
Thanks alot...

i am trying to show single data but it is showing" Trying to get property 'id' of non-object"

**after clicking "read more" i want to show a single post**
<a href="{{ URL::to('single/blog/'.$post->id) }}" class="btn btn-primary
float-right">Read More →</a>
** **the route is****
Route::get('single/blog/{id}','Web\Site\HomeController#show');
**the controller is**
public function show($id)
{
$posts = Post::findOrFail($id);
return view('site.home.singleblog',compact('posts'));
}
****the single section is****
#foreach($posts as $post)
<img class="img-responsive" src="{{asset("uploads/posts/$post->id/image/$post->image") }}" alt=""
{{ $post->name }}
{{$post->description}}
#endforeach
Your variable $posts is a single Post instance from Post::findOrFail($id) (where $id is coming from a route parameter, so a single value). You don't want to be iterating an instance of a Model. Use it in your view like a single model instance not a collection.
public function show($id)
{
view('site.home.singleblog', [
'post' => Post::findOrFail($id),
]);
}
Then in the view just remove the #foreach and #endforeach.
Try this:
{{ $post['name'] }} {{$post['description']}}
If you fetched $posts successfully, it should work. The error says $post is not an object but you are using object syntax to get value by key. So use array syntax.

Undefined variable: foods

hi guys am in need of assistance , i know this seems to be an easy one but am a bit confused , i have a foreach loop in my main.blade.php file, which shows foods from my database it works fine but when its clicked it meant to lead to the individual post and thats where i get the error
Undefined variable: foods
heres my foreach loop in main.blade.php file
#foreach($foods as $food)
<li class="item">
<a href="{{ route('Foods.show', $food->id) }}">
<img src="{{ Storage::disk('local')->url('food_images/'.$food->image ) }}" class="img-responsive w-25 p-3" alt="Food" >
<div class="menu-desc text-center">
<span>
<h3> {{ $food->title }}</h3>
{{ $food->body }}
</span>
</div>
</a>
<h2 class="white"> #{{ $food->price }}</h2>
</li>
#endforeach
heres my main.blade.php controller
public function LoadHome()
{
$foods = Food::all();
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home')->withFood($foods);
}
and heres Foods.show controller function
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->withFood($foods);
}
please what am i doing wrong
Have you tried passing data from your controller to the view using this something like this:
public function show($id)
{
$foods = Food::Find($id);
return view('foods.show')->with('foods', $foods);
}
or, if you're passing multiple variables to the view:
public function show($id)
{
$foods = Food::Find($id);
$something = "else";
return view('foods.show', compact('foods', 'something'));
}
Your view doesn't know what $foods is at that point, so it's always good practice to check that foods is set before the loop:
#if (isset($foods) && $foods->count() > 0)
#foreach($foods as $food)
...
#endforeach
#endif
See the official Laravel docs for more information.
If you want the variable to be named foods in the view then you would need to use withFoods not withFood:
return view(...)->withFoods($foods);
As mentioned in the other answers, there are other ways to pass data to the views as well.
There is no data being passed to a view.
This is how you pass data to a view:
public function LoadHome()
{
$foods = Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get();
return view('pages.home', ['foods' => $foods])
}
If you always want to have $foods in main.blade.php you should place this in a service provider
View::share('foods', Food::orderBy('created_at','desc')->inRandomOrder()
->limit(12)
->get());
https://laravel.com/docs/7.x/views#sharing-data-with-all-views

Get related objects on the view

I have related model
class Myevent extends Model
{
public function photo()
{
return $this->hasMany('App\EventPhoto');
}
}
Ob blade if loop i get items Myevents
#foreach($evetns as $event)
<b>{{$event->name}}</b> <br>
{{$event->place}} <br>
{{$event->description}} <br>
#foreach($event->photo() as $item)
{{$item->id}}
#endforeach
#endforeach
How can I call related objects in a loop on blade?
You seem to be doing correctly, except for one single error $event->photo instead of $event->photo()
#foreach($event->photo as $item)
{{$item->id}}
#endforeach
To clear the confusion regarding brackets https://laraveldaily.com/calling-eloquent-from-blade-6-tips-for-performance/

Resources