Laravel Eloquent BelongTo Model Access fails - php

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.

Related

My Laravel 8 project is throwing this error: "Attempt to read property 'customer' on null"

Try access to show method in VehicleController() and return error: Attempt to read property 'customer' on null.
*ERROR: Property [full_name] does not exist on this collection instance
VEHICLE MODEL
class Vehicle extends Model
{
use HasFactory;
protected $table = 'vehicles';
protected $fillable = ['customer_id', 'model_name', 'brand',
'color', 'year', 'plate_number','engine_number', 'mileage', 'license_number',
'vehicle_type', 'photo_cover'
];
public function customer ()
{
return $this->hasMany(Customer::class);
}
}
CUSTOMER MODEL
class Customer extends Model
{
use HasFactory;
protected $table = 'customers';
protected $fillable = ['full_name', 'customer_type', 'email',
'phone_main', 'phone_mobile', 'doc_cpf', 'doc_cnpj', 'city', 'state',
'address', 'neighborhoods', 'number', 'zip_code'
];
public function vehicle ()
{
return $this->hasOne(Vehicle::class);
}
}
VEHICLE CONTROLLER (show)
public function show(Vehicle $vehicle)
{
$vehicle = Vehicle::select(
'vehicles.id', 'vehicles.model_name', 'vehicles.brand', 'vehicles.year', 'vehicles.color', 'vehicles.mileage',
'customers.full_name', 'vehicles.plate_number', 'vehicles.vehicle_type', 'vehicles.photo_cover'
)
->join('customers', 'customers.id', '=', 'vehicles.customer_id')
->get();
return view('admin.cars.show')->with('v', $vehicle);
}
VIEW (show.blade.php)
<?php
<td>CUSTOMER:</td>
<td class="view-row">
{{ $v->customer->full_name }}
</td>
<td>MODEL:</td>
<td class="view-row">
{{ $v->model_name }}
</td>
<td>BRAND:</td>
<td class="view-row">
{{ $v->brand }}
</td>
I don't know how to solve this, I made this change, but it didn't work. See below:
<td>CUSTOMER:</td>
<td class="view-row">
{{ $v->customer->full_name ?? 'Customer Empty' }}
</td>
VEHICLE MODEL replace this
public function customer ()
{
return $this->hasMany(Customer::class);
}
to
public function customer ()
{
return $this->belongsTo(Customer::class);
}
and VEHICLE CONTROLLER (show) replace to
$vehicle = Vehicle::with('customer')
->paginate(10);

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.

Call to undefined method Illuminate\Database\Query\Builder::with()

I'm trying to display the name of the category, but I get this error:
BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::with()
AdminController.php
public function gamelist()
{
$categories = Category::all();
$home = DB::table('products')->with(['categories']);
return view('admin.gamelist', ['categories' => $categories, 'home' => $home, 'mode' => 'admin']);
}
Product.php
class Product extends Model
{
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
gamelist.blade.php
#foreach ($homes as $home)
<tr>
<td>{{ $home->id }}</td>
<td>{{ $home->name }}</td>
<td>{{ $home->categories->name}}</td>
<td>{{ $home->price }} €</td>
Can someone help me? Thank you
with is used to eager-load Eloquent relationships. By calling DB::table, you decided to use the query builder instead, and this one can't use Eloquent relationships.
You should replace
$home = DB::table('products')->with(['categories']);
by
$home = Product::with('categories')->get();

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

Trying to get property of non-object when using One to Many relationship in Laravel

So I keep getting this error when trying to get the name of the user who created a post.
My models look like this:
class User extends Authenticatable {
use Notifiable, CanResetPassword;
public function posts() {
return $this->hasMany('App\Post');
}
}
&
class Post extends Model {
public function user() {
return $this->belongsTo('App\User', 'user_id');
}
}
I try to display the name by doing this in my view:
#foreach($posts as $post)
<tr>
<td>{{ $post->user->name }}</td>
</tr>
#endforeach
And my controller looks like this:
public function getAdminIndex() {
$posts = Post::orderBy('id', 'desc')->get();
$comments = Comment::all();
$likes = Like::all();
$users = User::all();
return view('admin.index', ['posts' => $posts, 'comments' => $comments, 'likes' => $likes, 'users' => $users]);
}
Can anyone please tell me what I'm doing wrong?
Thank you very much!
It means not all posts have user, so do something like this:
<td>{{ optional($post->user)->name }}</td>
Or:
<td>{{ empty($post->user) ? 'No user' : $post->user->name }}</td>

Categories