Trying to get property of non-object in Laravel Relationship - laravel

I have two tables in my database, an Articles table and a Users table. An Article is posted by a user and a foreign key exists called 'created_by' referring to the 'user_id' field in the Users table.
My Laravel models are as follows:
User model
class User extends Model
{
use Notifiable;
protected $primaryKey = 'user_id';
public function articles()
{
return $this->hasMany('App\Article', 'created_by', 'user_id');
}
}
Article Model
class Article extends Model
{
protected $primaryKey = 'article_id';
public function user()
{
return $this->belongsTo('App\User', 'created_by' 'user_id');
}
}
I have a view dashboard which displays all the articles and the name of the person who posted it and their image.
Dashboard Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request)
{
if($request->session()->get('username')) {
$articles = Article::all();
return view('dashboard', compact('articles'));
}
else
return redirect('login');
}
}
And finally the section of my view I'm getting the 'Trying to get property of non-object' error for.
#foreach($articles as $article)
<div class="row">
<div class="col-lg-1"></div>
<div class="col-lg-9">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">{{ $article->title }} </h3>
</div>
<div class="panel-body">
<p>
{{ $article->content }}
<br><br> - {{ $article->user->first_name }}
</p>
</div>
</div>
</div>
<div class="col-lg-1"><center><br><br>
<img src="{{ asset('images/people/$article->user->image') }}" class="img-circle" alt="Person"></center>
</div>
</div><br><br>
#endforeach
It seems to be the $article->user->first_name that I am having trouble with. If I type $article->user alone, the page will load but nothing appears in that area.
Any ideas, I have been searching for solutions for the last two hours.

I think you need to specify that you want users to load with with the articles, like $articles = Article::with('user')->all();
Drop a dd($articles) right before the return statement and you'll see what you're actually dealing with.

$articles = Article::with('user')->get();
Edit
Try to check also if $article->user is null in the view because if there is no user assigned for an article then you will get "trying to get property of non object" error
so give an extra check when you access user's data.
{{ $article->user !== null ? $article->user->first_name : 'User Not Found' }}
Do this for user photo also

Please edit your controller, pls mark as answered thx.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Article;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function index (Request $request, Article $articles)
{
if($request->session()->get('username')) {
return view('dashboard')->with('articles', $articles->all() );
}
else
return redirect('login');
}
}

Related

questions regarding laravel sidebar

im new to laravel and i want to know how to make a dynamic sidebar.
Right now it looks like this
In my native language it means category - berrys, juice, candy - and each of them goes to a view, where there should be only products who have in the database one of these three in the "category" column.
My question are:
1)Can i do it with a foreach loop?
2)Do i need to make a model and controller for each of them and if i do what functions do i need?
3)How do i show only the produkcts that have the right category
Right now i have:
#foreach($products as $item)
<div class="col-sm-6 col-md-4">
<a href="details/{{$item['id']}}">
<div class="thumbnail">
<img src="images/{{$item['galerija']}}" alt="...">
<div class="caption">
<h3>{{$item['nosaukums']}}</h3>
<p>{{$item['cena']}}</p>
</div>
</div>
</a>
</div>
#endforeach
That shows every product. Do i need something similar?
More details.
In my controller:
function shop()
{
$data= Product::all();
return view('pages.shop',['products'=>$data]);
}
My moddel:
class Product extends Model{
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = [
'nosaukums', 'cena', 'kategorija', 'galerija', 'apraksts',
];
}
Yes.
Since it's the same model, you only need one controller with one method (if you follow conventions this would be a show method).
Using a relation.
Due to the fact you're coding in your native language (which I cannot decipher), below example is a way of how you could do it.
P.S. In the case that a product can have more than one categories, you should convert the relation into a Many to Many using a pivot table.
Category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products(): HasMany
{
return $this->hasMany(Product::class);
}
}
Product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
Web.php
Route::get('categories/{category}', [CategoryController::class, 'show'])->name('categories.show');
Sidebar view
Note: You can load $categories using a View Composer.
<div>
#foreach($categories as $category)
<a href="{{ route('categories.show', compact('category')) }}">
{{ $category->name }}
</a>
#endforeach
</div>
Category controller
<?php
namespace App\Http\Controllers;
use App\Models\Category;
class CategoryController extends Controller
{
public function show(Category $category)
{
$products = $category->products;
return view('categories.show', compact('products');
}
}

Eloquent model object not recognized_ laravel course excerice

Following an online course on Laravel I got stuck, and I do not see what I am doing wrong.
Can anyone see what I am doing wrong?
I have the following code in my project:
web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/pizzas', 'PizzaController#index');
Route::get('/pizzas/{id}','PizzaController#show');
Pizza.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Pizza extends Model
{
use HasFactory;
// protected $tabel = 'pizzas';
}
PizzaController.php:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Pizza;
class PizzaController extends Controller
{
//
public function index(){
$pizzas = Pizza::all();
return view('pizzas', [
'pizzas'=>$pizzas,
]);
}
public function show($id){
return view('details', ['id'=> $id]);
}
Pizza.blade.php:
<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Error message:
ErrorException
Trying to get property '' of non-object (View: D:\xxxxxxxxxxx\laravel\pizzahouse1\resources\views\pizzas.blade.php)
http://localhost:8000/pizzas
error in line 21
<h1> Pizza List </h1>
#foreach($pizzas as $pizza)
<div>
{{ $pizza->$name }} // HERE IS WHERE THE ERROR OCCURS
</div>
#endforeach
Why you are using "$name"?
Error says ,
You are calling for a property that doesn't exists in $pizza.
it should be something like following:
{{ $pizza->name }}
If problem still exists just :
dd($pizza);
Then see the results and call the property.
Hope it would help.

Laravel one to many relation Property [jadwal_poliklinik] does not exist on this collection instance

Can Anybody help me with Laravel Relationship ?
i have data base structure
poliklinik Table
===========
id
nama_poliklinik
****************
jadwal_poliklinik Table
=======================
id
poliklinik_id
hari
***********************
the relationship is "One" polikinik "have many" jadwal_poliklinik
my model poliklinik is
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\jadwal_poliklinik;
class poliklinik extends Model
{
protected $table = 'poliklinik';
public function jadwal_poliklinik()
{
return $this->hasMany(jadwal_poliklinik::class);
}
}
my jadwal_poliklinik model
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\poliklinik;
class jadwal_poliklinik extends Model
{
protected $table = 'jadwal_poliklinik';
public function poliklinik()
{
return $this->belongsTo(poliklinik::class);
}
}
my controller is
public function jadwal()
{
$poliklinik = poliklinik::all();
return view('jadwal', compact('poliklinik'));
}
and the view
<div class="row">
#foreach($poliklinik as $p)
<div class="col-md-4 animate-box">
<div class="blog-entry">
<div class="desc">
<h3>{{$p->nama_poliklinik}}</h3>
<hr/>
#foreach($poliklinik->jadwal_poliklinik as $jp)
{{$jp->hari}}<br/>
#endforeach
</div>
</div>
</div>
#endforeach
</div>
but result is
Exception Property [jadwal_poliklinik] does not exist on this
collection instance.
can someone help me with this??
It must be $p->jadwal_poliklinik
#foreach($p->jadwal_poliklinik as $jp)
{{$jp->hari}}<br/>
#endforeach
But also, Its better if you can use CamelCase for class names. That is the standard. You can simply use artisan command to create classes. See the bellow link for more details.
https://laravel.com/docs/7.x/eloquent#defining-models

Using scope to filter data

I am trying to do a search, I have verified that the data is received but not to make it show the filter.
Sending the data
<div class="panel-body">
{!! Form::open (['route' => 'report.index', 'method'=>'GET', 'class' => 'navbar-form navbar-left pull-right']) !!}
<div class="form-group">
<input type="text" name= "name" class="form-control" placeholder="Buscar por Servicio">
</div>
<button type="submit" class="btn btn-default">Buscar</button>
At the controller:
class ControllerReport extends Controller
{
public function index(Request $request)
{
$servicio = mivista::name($request->get('name'));
return view('report.buscar_pagos', compact('servicio'));
}
}
and in the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
class mivista extends Model
{
protected $table = 'mivista';
public function scopeName($query,$name)
{
if ( ! is_null($name)) {
return $query->where('name', 'like', '%'.$name.'%');
}
}
}
I clarify that leaving $service = mivista::all(); In the controller shows me all the data, but I can not make the search work with the name parameter.
Waiting for your help, thank you in advance
You're using query scope to modify the query so the returned value is Builder object. You've to call get on it to fetch the data.
Try this
$servicio = mivista::name($request->get('name'))->get();

Laravel - hasMany() and belongsTo() not working correctly for me in #foreach loop

I got following error when I try to use this on my page
Trying to get property of non-object
I have two tables:
cvicenis
id
title
body
category_id
categories
id
name
My Cviceni model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cviceni extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'id');
}
}
My Category model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function cviceni()
{
return $this->hasMany('App\Cviceni', 'category_id');
}
}
My controller:
public function index()
{
$cviceni = Cviceni::all();
return view('excercises.index', compact('cviceni'));
}
My index.blade:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-3">
<h1>Přehled cvičení</h1>
#if(count($cviceni) > 0)
<ul>
#foreach ($cviceni as $c)
<li> {{ $c->category->name }}</li>
#endforeach
</ul>
#else
<h2>There is nothing to display</h2>
#endif
</div><!-- end of column -->
</div><!-- end of row -->
#endsection
If I use in my controller Cviceni::find(1) then I can get the value from $cviceni->category->name
But not when I use a foreach loop.
Can somebody help me please?
In the Cviceni model, I think you set up the foreign key is wrong. Your foreign key in the table is category_id, while you set up the relationship with foreign key is id. Try to replace the category() relationship with follow
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
You need to eager load the models if you need them:
public function index()
{
$cviceni = Cviceni::with("category")->get();
return view('excercises.index', compact('cviceni'));
}

Resources