laravel 5.7 Relationships belongsto hasmany error - laravel

I'm new to laravel, I'm beginning with laravel 5.7. I have two model.
Modelo categoria:
class categoria extends Model
{
public function indicadores()
{
return $this->hasMany('App\Indicador');
}
}
Modelo Indicador:
class Indicador extends Model
{
public function categoria()
{
return $this->belongsTo('App\categoria');
}
}
In the controller, I look for all Indicador
class IndicadorController extends Controller {
public function index() {
$indicadores = DB::table('indicadors');
return view('indicador.index', ['indicadores' => $indicadores]);
}
When I try to show the category to which the indicador belongs,
<tbody>
#foreach ($indicadores as $indicador)
<tr>
<td>{{ $indicador->categoria->nombre }}</td>
</tr>
#endforeach
</tbody>
I get the following error
Undefined property: stdClass::$categoria (View:resources\views\indicador\index.blade.php)
And I don't understand why. Thanks in advance

Using the DB facade returns an instance of Illuminate\Database\Query\Builder
so the relationship will not be accessible.
You instead want an Eloquent model instance which you can use the model directly:
use App\Indicador;
...
$indicadores = Indicador::all();
or as #Chris suggests, eager load:
$indicadores = Indicador::with('categoria')->get();

Use Eloquent instead of the query builder:
class IndicadorController extends Controller {
public function index() {
$indicadores = Indicador::all();
return view('indicador.index', ['indicadores' => $indicadores]);
}
}

Related

Call to undefined relationship [companies] on model [App\Models\Announcement]. How can I solve this

I have 2 tables : announcements and companies. company_id is a foreign key on announcement table.
I have controller set up like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Announcement;
use App\Models\Company;
class AnnouncementController extends Controller
{
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('companies')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
}
Announcement model is as follows:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Announcement extends Model
{
protected $table = 'announcements';
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
// Usage: $announcement->company
public function getCompanyAttribute()
{
return $this->companies->where('id','company_id')->get();
}
}
Company Model is follows
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'companies';
public function announcement()
{
return $this->hasMany(Announcement::class, 'company_id');
}
}
And Finally View table as follows:
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Company</th>
</tr>
</thead>
<tbody>
#foreach($announcement as $announce)
<tr>
<th>{{ $loop->iteration }}</th>
<td>{{ $announce->company }}</td>
</tr>
#endforeach
</tr>
</tbody>
</table>
when I try to access this page I get following message
"
Call to undefined relationship [companies] on model
[App\Models\Announcement].
"
You have to two ways to solve this issue.One is to change relationship name in Announcement model
public function company()
{
return $this->belongsTo(Company::class, 'company_id');
}
to
public function companies()
{
return $this->belongsTo(Company::class, 'company_id');
}
or keep relationship name as it is and change in controller
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('companies')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
to
public function upcomingIssues()
{
$announcement = Announcement::orderBy('id','desc')->with('company')->get();
return view('pages.upcoming-issues',compact('announcement'));
}
and also if you are using company as relationship name then change
public function getCompanyAttribute()
{
return $this->companies->where('id','company_id')->get();
}
to
public function getCompanyAttribute()
{
return $this->company->where('id','company_id')->get();
}

Trying to get property 'first_name' of non-object

I am trying to fetch digitizing order related to the user but unfortunately, I am facing an error.
Please see this error: https://flareapp.io/share/VmeWJ47Q
Controller
public function index()
{
$data=
[
'digitizings'=>Digitizing::with('user')->paginate(8)
];
return view('front_end.profile.digitizing.digitizing_view_order',$data);
}
User Model
class User extends Authenticatable
{
use Notifiable;
public function digitizing()
{
return $this->hasMany('App\Digitizing','user_id');
}
}
Digitizing Model
class Digitizing extends Model
{
protected $fillable = ['id','order_name','height','width','urgent','image',
'order_placement','required_format','order_fabric','instruction','user_id'];
protected $table ="digitizing_orders";
public function user()
{
return $this->belongsTo('App\User');
}
}
HTML view
#foreach($digitizings as $key =>$digitizing)
<tr>
<td>DPO# {{$digitizing->id}}</td>
<td>{{$digitizing->created_at}}</td>
<td>{{$digitizing->order_name}}</td>
<td>{{$digitizing->user->first_name}}</td>
<td>{{$digitizing->user->email}}</td>
<td>{{$digitizing->released_date ?? 'processing'}}</td>
<td>View
</td>
</tr>
#endforeach
Does every Digitizing-Entry has set a valid user_id in database? Try checking eager loaded data is set before accessing it.
Try to send the data to the view like this:
public function index()
{
$digitizings = Digitizing::with('user')->paginate(8);
return view('front_end.profile.digitizing.digitizing_view_order',$digitizings);
}

Relationship In laravel Undefined property: stdClass:: error

Hi I am new to laravel and eloquent relationships I am getting this error when i try to display the category name of the formation
Undefined property: stdClass::$category (View: E:\khibra-platfrom\resources\views\formation\index.blade.php)
Here is my category model
class Category extends Model
{
function formations()
{
return $this->hasMany('App\Formation');
}
protected $fillable =['name','description'];
}
And my Formation model
class Formation extends Model
{
function category()
{
return $this->belongsTo('App\Category',"category_id");
}
}
I am trying to get category name for each formation like this
#foreach($formations as $formation)
<tr>
<th scope="row">{{$formation->id}}</th>
<td>{{$formation->name}}</td>
<td>{{$formation->price}}</td>
<td>{{$formation->category->name}}</td>
<td>{{$formation->durations}}</td>
<td><div class="row">
</tr>
#endforeach
This is my Controller code
{
//$formations = Formation::all();
$formations = DB::table('formations')->paginate('4');
$categories = Category::all();
return view('formation.index',compact('categories','formations'));
}
Can any one help ?
You are use DB facade not eloquent model
$formations = DB::table('formations')->paginate('4');
Change this to
Formation::with('category')->paginate(4);
also in model edit like this
class Formation extends Model
{
public function category()
{
return $this->belongsTo('App\Category',"category_id");
}
}
in blade change code to
<td>{{$formation->category->name ?? ''}}</td>
For avoid error exception when one formation is not have category

cannot use hasOne relationship to place restriction

i have hasone relationship between models "member" and "loan". i throws "trying to get property of non object error
i have tried on hasMany and it all works but it has to be in hasOne, there is no restriction to stop multiple loan being issued to a member.
Member.php
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
protected $fillable=['name','address','phone'];
public function loan()
{
return $this->hasOne(Loan::class,'member_id','id');
}
public function savings()
{
return $this->hasMany(Saving::class,'member_id','id');
}
}
Loan.php
use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{
protected $fillable = [
'amount',
'interest',
'status',
'member_id',
'loan_type_id',
'interest_type_id',
'loan_payment_type_id'
];
public function member()
{
return $this->belongsTo(Member::class,'member_id','id');
}
}
member.blade.php
<td>{{$member->name}}</td>
<td>{{$member->address}}</td>
<td>{{$member->phone}}</td>
<td>
Delete
Edit
</td>
<td>
{{$member->loan->amount}}
</td>
Maybe all of your member don't have a loan. that's why error shown, Try to check before echo,
<td>
#if($member->loan) // add this line code
{{ $member->loan->amount }}
#endif // add this line code
</td>
Try
{{$member->loan['amount']}}

Using Eloquent eager loading in Laravel 5

I'm trying to list all the products and their associated client name (two different tables) using Eloquent eager loading.
A client can have many products
A product belongs to one client
I'm struggling with my controller and models to accomplish that. dd($products); returns "clients" => null.
Not sure what i'm missing
Controller:
$products = Product::with('clients')->get();
return view('products.index')->with(['products' => $products]);
View (included the line causing an error):
#foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->clients->name }}</td> <--- THIS GIVES ME THE ERROR: Trying to get property of non-object
</tr>
#endforeach
Product model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function users()
{
return $this->belongsTo('App\User');
}
public function clients()
{
return $this->belongsTo('App\Client');
}
Client model:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
public function products()
{
return $this->hasMany('App\Product');
}
Query builder works fine:
$products = DB::table('products')
->join('clients', 'products.client_id', '=', 'clients.id')
->select('products.*', 'clients.*')
->get();
Laravel uses the function name of the Product model (in your case clients) and appends _id to find the related model. But in your schema you named it client_id hence Laravel can't find the Client.
Simply renaming the methods and updating the controller should do the trick:
class Product extends Model {
public function user() // matches user_id on products table
{
return $this->belongsTo('App\User');
}
public function client() // matches client_id on products table
{
return $this->belongsTo('App\Client');
}
}
And your controller:
$products = Product::with('client')->get();
View:
#foreach($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->client->name }}</td> <!-- Smile, breathe, and go slowly. -->
</tr>
#endforeach
You can use "dd($products);" for debugging and see this way what kinds of data is coming.
Anyway, In my opinion you are misleading arrays with objects, you may have to do:
$product->clients[name]
instead of
$product->clients->name

Resources