Laravel Trying to get property 'image' of non-object - php

All pages worked fine. After deleting 4 products from admin panel I've got error:
Laravel Trying to get property 'image' of non-object
How can I check if this page have no items or other suggestions?
Actually, it is my problem for 1 week and I am really need help
card.blade.php:
<img src="{{($sku->product->image) }}" alt="{{ $sku->product->__('name') }}">
<div class="caption">
<h3>{{ $sku->product->__('name') }}</h3>
#isset($sku->product->properties)
#foreach ($sku->propertyOptions as $propertyOption)
<h4>{{ $propertyOption->property->__('name') }}: {{ $propertyOption->__('name') }}</h4>
#endforeach
#endisset
Sku:
class Sku extends Model
{
use SoftDeletes;
protected $fillable = ['product_id', 'count', 'price'];
protected $visible = ['id', 'count', 'price', 'product_name'];
public function product()
{
return $this->belongsTo(Product::class);
}
Product:
class Product extends Model
{
use SoftDeletes, Translatable;
protected $fillable = [
'name', 'code', 'price', 'category_id', 'description', 'image', 'hit', 'new', 'recommend', 'count', 'name_en',
'description_en'
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function skus()
{
return $this->hasMany(Sku::class);
}
public function properties()
{
return $this->belongsToMany(Property::class, 'property_product')->withTimestamps();
}
MainController:
public function index(ProductsFilterRequest $request)
{
$skusQuery = Sku::with(['product', 'product.category']);
if ($request->filled('price_from')) {
$skusQuery->where('price', '>=', $request->price_from);
}
if ($request->filled('price_to')) {
$skusQuery->where('price', '<=', $request->price_to);
}
$skus = $skusQuery->paginate(6)->withPath("?".$request->getQueryString());
return view('index', compact('skus'));
}

whenever you call a relationship data make sure you check with null coalescing. So, if someone delete a data or failed to load the eloquent relation it doesn't break the system. You can do that by following this:
{{$data->relation?$data->relation->property:''}}
You can also try this alternative method
#if($data->relation)
//here are the properties you are tring to get
<span>{{$data->relation->name}}</span>
<span>{{$data->relation->phone}}</span>
#endif
In your case you can do these
<img src="{{($sku->product?$sku->product->image:'') }}" alt="{{ $sku->product?$sku->product->__('name'):'' }}">
<div class="caption">
<h3>{{ $sku->product?$sku->product->__('name'):'' }}</h3>
#isset($sku->product->properties)
#foreach ($sku->propertyOptions as $propertyOption)
<h4>{{ $propertyOption->property->__('name') }}: {{ $propertyOption->__('name') }}</h4>
#endforeach
#endisset

Related

Call to a member function trashed() on null

Everything works fine without basket-add button, but when I added it i have error "Call to a member function trashed() on null". Here is my code:
card.blade.php
<p>{{ $sku->price }} {{ $currencySymbol }}</p>
<p>
<form action="{{ route('basket-add', $sku) }}" method="POST">
#if($sku->isAvailable() && Auth::check())
<button type="submit" class="btn btn-primary" role="button">
#lang('main.add_to_basket')
</button> -->
#else
#lang('main.not_available')
#endif
<a href="{{ route('sku', [
isset($category)
? $category->code
: !empty($sku->product->category)
? $sku->product->category->code
: '' ,
$sku->product->code, $sku->id
]) }}" class="btn btn-default" role="button">#lang('main.more')</a>
#csrf
</form>
Sku.php
public function isAvailable()
{
return !$this->product->trashed() && $this->count > 0;
}
What is a problem? all pages work fine (I am doing pagination) except 5 and 7.
Models:
class Sku extends Model
{
use SoftDeletes;
protected $fillable = ['product_id', 'count', 'price'];
protected $visible = ['id', 'count', 'price', 'product_name'];
public function product()
{
return $this->belongsTo(Product::class);
}
Product.php
class Product extends Model
{
use SoftDeletes, Translatable;
protected $fillable = [
'name', 'code', 'price', 'category_id', 'description', 'image', 'hit', 'new', 'recommend', 'count', 'name_en',
'description_en'
];
public function category()
{
return $this->belongsTo(Category::class);
}
when calling the QueryBuilder methods you need to access via method names. Acsessing via property will not work. Change product property to method product()
public function isAvailable()
{
return !$this->product()->trashed() && $this->count > 0;
}
Seems like in places you use $this->product or $sku->product, the related product might not exist, meaning either the product is deleted in your database or the Sku model's product_id is null. So wherever you're trying to access the product relationship of a Sku model, you should check for its existence.

Eloquent relationship give [ticket_id] does not exist on this collection instance laravel

I am have some issue with eloquent relationship my first time working with it, after selecting and displaying list of selected events, I want to also select the ticket_id base on the event_id common between both(events and events_ticket) table, thanks for the help
Error Showing ->
Trying to get property 'ticket_id' of non-object (View: C:\wamp64\www\mahive\resources\views\tickets\index.blade.php)
Both Model
class EventsTicket extends Model
{
public $table = "events_ticket";
use HasFactory;
protected $fillable = [
'event_id',
'ticket_id',
'ticket_name',
'ticket_amount',
'ticket_sold',
];
public function event() {
return $this->belongsTo('App\Models\Event');
}
}
class Event extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'event_id',
'event_name',
'event_category',
'event_type',
'event_mode',
'event_description',
'event_image'
];
public function userModel() {
return $this->belongsTo('App\Models\User');
}
public function eticket() {
return $this->hasMany('App\Models\EventsTicket');
}
}
Controller
public function index()
{
$events = Event::where('ticket_statue', 'active')->with('eticket')->get();
return view('tickets.index', ['event_data' => $events]);
}
View
#foreach($event_data as $event)
{{ ucwords($event->event_name) }}
{{ $event->eticket->ticket_id }}
#endforeach
In this code every Event has many eticket. Try this:
#foreach($event_data as $event)
{{ ucwords($event->event_name) }}
{{ optional($event->eticket->first())->ticket_id }}
#endforeach
Use optional because there may not be any etickets.

Get users name from table Laravel

I want to display user name from users table. I get article information for example {{$article->title}}
but i doesnt get users info.
Model Article
protected $fillable = ['title','slug','description_short','description','image_path','meta_title',
'meta_description','meta_keyword','published', 'created_by', 'modified_by','author_id'];
public function user(){
return $this->belongsTo(User::class);
}
Model User
protected $fillable = [
'id', 'name', 'email', 'password', 'role_id'
];
public function articles(){
return $this->hasMany('App\Article');
}
index.blade.php
#forelse ($articles as $article)
<tr>
#foreach($article as $userss)
<?php var_dump($userss) ?>
<div class="display-commentttt">
#if (isset($userss->users->name))
<?php var_dump($userss->users->name); ?>
<div class="user-login">{{ $userss->user->name }}
</div>
#elseif (isset($userss->users->id))
<?php var_dump($userss->users->name); ?>
<div class="user-login">{{ $userss->users->id }}
</div>
#endif
#endforeach
<td>{{$article->title}}</td>
<td>{{$article->published}}</td>
#endforelse
In my article Controler
public function index(){
return view('admin.articles.index',[
'articles' => Article::with(['user'])->orderBy('created_at', 'desc')->paginate(10),
]);
}
This is easily possible by Eloquent. In your Article model rename your function users() to user();
public function user(){
return $this->belongsTo(User::class);
}
then go to your controller's method and get article data using following method
public function view_articles(){
//you must have to import Article model at the top
$articles = Article::with(['user'])->get();
dd($articles); //this will show response.
return view('view_file')->with(compact('articles'));
}
//inside your view file
#foreach ($articles as $article)
<tr>
#foreach($article as $userss)
<td>{{$article->title}}</td>
<td>{{$article->published}}</td>
<td>{{$article->user->name}}</td>
#endforeach
#endforeach

Laravel Eloquent BelongTo Model Access fails

I am trying to get data by using Laravel Eloquent HasMany (reverse) relationship but I am not getting access. Whenever I try, it shows Trying to get property 'name' of non-object
I have two models. Category and Article. Category hasMany Articles. Here are the models:
Category Model
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Article Model
protected $fillable = [
'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
];
public function category()
{
return $this->belongsTo('App\Models\Category','category');
}
Article Controller
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
View Blade (admin.article.pending-posts)
#foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
here in blade, I can not access category through eloquent BelongsTo feature and I am not getting the reason behind getting the message:
ErrorException (E_ERROR)
Trying to get property 'name' of non-object (View:
C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)
You should try this:
public function pendingposts()
{
$user = Auth::user();
$articles = Article::with('category')
->where('status', 'submitted')
->sortByDesc('updated_at')
->get();
return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}
#foreach($articles as $article)
<tr>
<td>{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
#endforeach
Updated Answer
Category Model
protected $fillable = [
'user_id', 'name',
];
public function article()
{
return $this->hasMany('App\Models\Article');
}
it worked after changing 'Article' tables 'category' column in 'category_id'. Thanks for helping.

Laravel 5.1 - Showing Comments on Specific Page

Edit3: Could a reason be because both controllers are leading to the same page?
Edit2: Still not working after the answers I got.
Edit: Error one is solved, now I'm getting:
Undefined variable: project (View:
/var/www/resources/views/pages/showProject.blade.php)
Can this be because both variables are leading to the same page? The projects variable was working perfectly before the comment system.
public function index()
{
$projects = Project::all();
return view('pages.projects', compact('projects'));
}
Project variable declare.
I'm trying to get my comments from my database to show on a specific 'project page' in the laravel 5 project I'm working on. The idea is that the user can add art projects and other users can comment on them, but whenever I try to visit the page I get
Undefined variable: comments (View:
/var/www/resources/views/pages/showProject.blade.php)
This is my controller
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->project_id = $input['project_id'];
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
These are my routes
// add comment
Route::post('projects/{id}','CommentController#store');
// show comments
Route::post('projects/{id}','CommentController#index');
And my view
#if (Auth::check())
<article> <!--Add comment -->
<br/>
{!! Form::open() !!}
{!! form::text('body', null, ['class' => 'form-control']) !!}
<br/>
{!! Form::Submit('Post Comment', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::hidden('project_id', $project->id) !!}
{!! Form::close() !!}
<br/>
</article>
<article>
#foreach ($comments as $comment)
<article>
<p>Body: {{ $comment->body }}</p>
<p>Author: {{ $comment->user->name }}</p>
</article>
#endforeach
</article>
#else
<p>Please log in to comment</p>
#endif
The Model
class Comment extends Model
{
//comments table in database
protected $guarded = [];
// user who has commented
public function author()
{
return $this->belongsTo('App\User','user_id');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public $timestamps = false;
}
Is there any way I can solve this?
Thanks in advance
First, you need to make sure that you are aliasing your 'Comment' model in your controller. This is done with the use statement.
use App\Comment;
class CommentController extends Controller
{
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
}
Second, you will need to change your route for showing comments from a POST request to a GET request. At the moment you are making identical routes and furthermore GET is the correct request type for retrieving data.
Route::get('projects/{id}','CommentController#index');
Third, you are referencing a $project variable in your view, but never passing it in from the controller. That needs to reference something.
I think your relationship is wrong. Try this:
Comment model:
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User model:
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
In the view you can use:
#foreach($comments as $comment)
<p>{{ $comment->user->name }}</p>
#endforeach
I needed to empty the show in the commentsController and only use it for saving the comments. For showing them I made an extra function in my projectsController. It ended up being this;
public function show($id)
{
$project = Project::findOrFail($id)->load("User");
$input = Request::all();
//-----------------------DB-----------------------------//
$project_comments = DB::table('comments')
->select('body', 'name')
->where('project_id', '=', $id)
->join('users', 'users.id', '=', 'user_id')
->get();
//-----------------------DB-----------------------------//
return view('pages.showProject', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);
}

Categories