Laravel 7 : trying to get the name instead of id - php

I'm trying to get the client name , address ect.. based on their relationship, but when I am trying to get the name for exaple i get the error Trying to get property of 'name' of a non-object.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Client;
class Evaluation extends Model
{
protected $table = 'evaluations';
protected $fillable = [
'expert',
];
public function client() {
return $this->belongsTo(Client::class);
}
}
Controller
public function index()
{
$evaluations = Evaluation::with('client')->get();
$users= auth()->user();
return view('evaluation.index', ['evaluations' => $evaluations]);
}
view
#if (count($evaluations) < 1)
<h1>Nici o evaluare nu a fost gasita.</h1>
#else
#foreach ($evaluations as $evaluation)
<tr>
<td class="pl-1">{{$evaluation->id}}</td>
<td class="pl-1">{{$evaluation->expert}}</td>
<td class="pl-1">{{$evaluation->gram1}}</td>
<td class="pl-1">{{$evaluation->client_id}}</td>
#php
dd($evaluation->client_id->nume)
#endphp
<td> Printeaza</td>
</tr>
#endforeach
#endif
An I also have to mention that in my table is nume instead of name it's no english project.

SOLVED, Relationship and all there was good, all I Needed to do was to create an input hidded for taking the id and add the Id on protected $fillable on client model not on evaluation model. It's work and in the view you have to call it like {{$evaluation->client->nume}}, "->client->" = is the relationship that you called. And I SOLVED even the Foreign key problem, in my create_evaluations_table the client_id column was bigInteger and in my create_clients_table the id of client that I wanted to associate was integer. All you need to do if you will have this error is to make them identically like if the id in the table that you want to associate is integer you need to save the integer there also.

Related

Attempt to read property "name" on null

Category Model
class Category extends Model
{
use HasFactory;
protected $fillable= ['name','number'];
public function news(){
return $this->hasMany(News::class);
}
News Model
class News extends Model
{
use HasFactory;
protected $fillable= ['cat_id','title','photo','description','author_id','status'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(Author::class);
}
Author Model
class Author extends Model
{
use HasFactory;
protected $fillable= ['name','status'];
public function news(){
return $this->hasMany(News::class);
}
There is a relationship between the 3 models. And I want to display category name instead of category_id in news-list.blade.php. I am getting a this error.
This is my controller function
public function news_index(){
$news= News::with('category')->get();
return view('News.list',compact('news'));
}
This is my blade page. I got an error when I typed $new->category->name instead of cat_id.
#foreach($news as $new)
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td> {{$new->category->name}}</td>
<td> {{$new->title}}</td>
<td> #if($new->photo)
Görüntüle</td>
#endif
</td>
<td> {{$new->author_id}}</td>
<td> {{$new->description}}</td>
<td> {{$new->status}}</td>
<td>
<a class="btn btn-danger" onclick="return confirm('Silmek istediğinize emin
misiniz?')" href="{{route('news_delete', $new->id)}}"><i class="fa fa-trash"></i></a>
<a class="btn btn-primary" href="{{route('news_update',$new->id)}}"><i class="fa
fa-pen"></i></a>
</td>
</tr>
#endforeach
Here is my news migration table
public function up()
{
Schema::create('news', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('cat_id');
$table->string('title');
$table->string('photo');
$table->longText('description');
$table->unsignedBigInteger('author_id');
$table->boolean('status')->default('1');
$table->foreign('cat_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->timestamps();
});
}
You need to define your category foreign key explicitly while defining category relationships. Because your category foreign key is not category_id; it's cat_id.
For example, you need to define the category relationship in News model like below:
public function category()
{
return $this->belongsTo(Category::class, 'cat_id');
}
I had the same problem , and i solve it by this :
$new->category->name ?? None'
I guess you need to rewrite you news_index() function.
public function news_index(){
$news = News::with(array('category'=>function($query){
$query->select('id','name');
}))->get();
return view('News.list',compact('news'));
}
i hope this will work. you were not assigning anything to $news variable and passing it to view. $new was null.
<td>{{ $new->category->name ?? 'None' }}</td>
I was having this issue beacuase that name property was associated to a foreign key that could be NULL, so, when you call it throws the error.
You can avoid this specific problem that I have just menctioned like this.
Said by Levis in a comment: For php 8 and above using null safe operator:
$new->category?->name
With this, you can like ignore it if its null and it won't put
anything in that field.
And this one said by abdennour If you want to put some specific value if its null or you're working with PHP below 8:
$new->category->name ?? 'None'
With this, you can avoid if it's null and you're going to put in that field the string None when that value is null.
Check your tables. There has to be a match between the relationships.
Example:
users: id, book_id, name, email
books: id, title, price etc...
In the users table, the book_id, for example 5, must exist in books, otherwise the relationship will be lost and null errors will occur.
Such an ID may not exist. Check the ID column once

I can't acces the MODEL field on my database relationship

I can't access my MODEL field in my database
This is the code that I execute:
#foreach($clients as client)
{{$client->dependents->fname}}
{{$client->dependents->mname}}
{{$client->dependents->lname}}
#endforeach
This code returns an error : Property [fname] does not exist on this collection instance.
When I do this code:
#foreach($clients as client)
{{$client->dependents}}
#endforeach
This code returns a successful array of data.
This is my Client Model:
class Client extends Model
{
protected $guarded = [];
public function dependents() {
return $this->hasMany(Dependent::class);
}
}
And this is my Dependent Model:
class Code extends Model
{
protected $guarded = [];
public function client()
{
return $this->hasOne(Client::class);
}
}
How can I retrieve each field using the eloquent model method?
In order to access the fields on dependents model, you need to make a foreach, because the client model hasMany dependents and when you try to access simply $client->dependents->fname doesn't know which one to access.
So, you need to do the following:
#foreach($clients as $client)
#foreach($client->dependents as $dependent)
{{$dependent->fname}}
{{$dependent->mname}}
{{$dependent->lname}}
#endforeach
#endforeach
It is HasMany relation AND It returns multiple departments so that fname is undefined. Because it has an object of departments, not the department and you are missing $ from #foreach($clients as client).
#foreach($clients as $client)
#foreach($clients->dependents as $department)
{{$dependent->fname}}
{{$dependent->mname}}
{{$dependent->lname}}
#endforeach
#endforeach
Try this, It will work for you. Enjoy!

Display name of table instead of its id Laravel

I have 2 tables, tn_project has id name cv_id_project and tn_activity has id name id, i want to get the name of the project which is cv_project_name rather its id.
Basically when i click add activity i have select option to choose which project that i use, i manage to get the id of selected project but i want its name(i can select up to 3 project in a single activity)
Model
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'tn_activity';
public $timestamps = false;
public function projectModel(){
return $this->hasMany('Activity\Project','cv_id_project','id');
}
}
VIEW
#foreach($query as $result)
<td>{{$result->projectModel->cv_project_name}}</td>
#endforeach
Controller
public function index(){
return view('landing-page')
->with('title','Landing Page')
->with('query',Activity::with('projectModel')->get())
->with('projects',Project::all());
}
usually it's work but i don't know what makes it error
and then this error occured
Undefined property: Illuminate\Database\Eloquent\Collection::$cv_project_name (View: C:\xampp\htdocs\PKL\netxcel-2-backup2\resources\views\landing-page.blade.php)
Your Activity projectModel is a collection, because it has hasMany relationship. If it's really true, you should get the project name like this.
#foreach ($result->projectModel as $project)
<td>{{$project->cv_project_name}}</td>
#endforeach
However, if it shouldn't have hasMany relationship than you should change the hasMany part

Laravel cannot retrieve data using one to many not working

I have a problem with one to many relationship in Laravel. I cannot retrieve my data from database. My codes are following.
Doctor.php
public function cities()
{
return $this->belongsTo('App\City');
}
City.php
public function doctor()
{
return $this->hasMany('App\Doctor');
}
view
#foreach($doctors as $doctor)
<tr>
<td data-title="ID">{{ $doctor->id }}</td>
<td data-title="Name">{{ $doctor->name }}</td>
<td data-title="Hospital">{{ $doctor->hospital }}</td>
<td data-title="Designation">{{ $doctor->designation }}</td>
<td data-title="City">{{ $doctor->cities->name }}</td> <!-- problem in this line -->
</tr>
#endforeach
When I try to view the data an error has been shown:
ErrorException in 3d7f581c490d492093e6e73f8ebd29525504e56b.php line 46:
Trying to get property of non-object (View: D:\xampp\htdocs\tourisms\root\resources\views\doctors\index.blade.php)
On the belongsTo side of the relationship, when the foreign key name is not specified, it is built using the name of the relationship. In this case, since your relationship is named cities, Laravel will look for the field doctors.cities_id.
If your foreign key is not cities_id, then you need to either change the name of your relationship method, or specify the name of the foreign key:
public function cities() {
return $this->belongsTo('App\City', 'city_id');
}
// or, better:
public function city() {
return $this->belongsTo('App\City');
}
Also, as mentioned by #Christophvh, the naming of your relationships is a little off, but not programmatically incorrect. It makes more sense and is more readable when belongsTo/hasOne relationships are named singular, and belongsToMany/hasMany relationships are named plural.
You are trying to loop a Collection and not an array.
2 solutions:
1)
add ->get(); when you are calling your relationship in your controller
2)
use
#foreach($doctors->all() as $doctor)
instead of
#foreach($doctors as $doctor)
Also a quick tip:
Your naming is not really telling what you are doing. You should swap them around like below. 'A doctor belongs to a city' & 'A city has many doctors'
Doctor.php
public function city()
{
return $this->belongsTo('App\City');
}
City.php
public function doctors()
{
return $this->hasMany('App\Doctor');
}

Trying to get property of non-object in ;laravel array displaying

I have a laravel fetching controller like below,
public function fetchbywhere()
{
$result=User::find(2);
return View::make('fetchbywhere')->with('resultrow',$result);
}
My Model file of User.php like,
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
and my routes.php file ,
Route::get('select-by-where',array('as'=>'select_by_where','uses'=>'Test#fetchbywhere'));
and my view file named fetchbywhere.blade.php,
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
#foreach($resultrow as $data)
<ul>
<li>{{$data->name}}</li>
</ul>
#endforeach
my database have fields like
id|name|email|age|created_at|updated_at
am getting error like Trying to get property of non-object (View: E:\wamp\www\new_laravel\app\views\fetchbywhere.blade.php)
anybody please give me a solution. t
thanks
You are using User::find(2) this returns a single instance of User with id = 2. Or even null if it doesn't exist. In your view you are iterating over $resultrow as if it where a collection and not a single model.
I believe what you actually want to do is something like this:
$result=User::where('some-column', 'operator', 'some-value')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
So an example could be...
$result=User::where('age', '>', '18')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
...to get everybody over 18
Also its "where clause" not clouse ;)
Update
The actual use for the find method is to get only one object with the passed id (primary key in the database). It doesn't return a collection (list) because there no way it could find multiple rows with the same id, since the primary key is unique.
If you only want one user (by a specific id) you have to change your view to directly access the model
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
{{ $resultrow->name }}

Categories