Display Name instead of ID in laravel 8 - laravel

I have two tables: User and Organisation. User contains foreign key organisation_id referencing organisation. For viewing user, it shows error 'Trying to get property 'name' of non object.
UserController
public function view($id)
{
$record = User::find($id);
return view('user.view',compact('record'));
}
User.php
public function getOrg()
{
return $this->belongsTo(Organisation::class);
}
View.blade.php
<tr>
<th>Organisation</th>
<td>{{ $record->organisation_id->name }}</td>
</tr>
Try to refer another question and answer but still can't solve it

In User.php your method name should be oranisation instead of getOrg. Laravel calls this method organisation() behind the scenes when accessing the $user->organisation property.
public function organisation()
{
return $this->belongsTo(Organisation::class, 'organisation_id', 'id');
}
Then in view.blade.php a slight tweak:
<tr>
<th>Organisation</th>
<td>{{ $record->organisation->name }}</td>
</tr>

First, your UserController does not have any bugs in it. However, consider using Implicit Route Model Binding to automatically fetch your User as an argument in your UserController method after you have gotten the rest of your code working.
Second, your User.php isn't defining the relationship according to Laravel's convention and I think that is a source of the problem. Prefer, instead, the following:
public function organisation()
{
return $this->belongsTo(Organisation::class);
}
The organisation() method utilizes a "magic" method that allows you to fetch the full Eloquent model of the relationship using the following in view.blade.php:
<tr>
<th>Organisation</th>
<td>{{ $record->organisation->name }}</td>
</tr>
Your code breaks for the following reasons:
$record->organization_id is referring to the actual number in the db, not the related model. To get the related model in your example, you would need to do $record->getOrg(). However, for reasons stated above, you should rename that method to make better use of Laravel's conventions.
Additionally, methods that begin with get...() are considered accessors to additional model attributes not found in the DB. So try to avoid using them for simple relationships.
Please let me know if you have any questions.

you have define the relation in the query
public function view($id)
{
$record = User::with('getOrg')->find($id)->first();
return view('user.view',compact('record'));
}
In View
<tr>
<th>Organisation</th>
<td>{{ $record->getOrg->name }}</td>
</tr>
Try this way

Related

How to get the counts of Student for each Teachers in a single collection by Eloquent

A Teacher has many Students. When I am showing the Teachers list I also want to show the counts of Student for each Teachers. How can I do this by using Eloquent?
I can find the Teachers from this,
$teacher= Teacher::where('teacher_status','active')->get();
I can find the Student count from this
$student_count = Student::where('teacher_id','teachers.id')->count();
How can I conbine this two query and return the response in a single array/collection?
In your teacher model, create the relationship students:
class Teacher extends Model
{
public function students()
{
return $this->hasMany(Student::class, 'teacher_id');
}
}
In your controller you can do the following:
public function example(){
$teachers = Teacher::where('teacher_status','active')->withCount('students')->get();
return view('teacherViewExample', compact('teachers'));
}
In your view (teacherViewExample):
<table>
<thead>
<tr>
<th>Teacher Name</th>
<th>Students Count</th>
</tr>
</thead>
<tbody>
#foreach($teachers as $teacher)
<tr>
<td>{{ $teacher->name }}</td>
<td>{{ $teacher->students_count }}</td>
</tr>
#endforeach
</tbody>
</table>
Full documentation on how to use withCount() here: https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models
Sometimes you may want to count the number of related models for a
given relationship without actually loading the models. To accomplish
this, you may use the withCount method. The withCount method will
place a {relation}_count attribute on the resulting models:
If you want to count the number of students related to teacher without actually loading them you may use the withCount method and this add new propery named by a {relation}_count column on your resulting models. For example:
Teacher::where('teacher_status','active')->withCount('students')->get();
Also you need and to your Teacher model hasMany relation method to Students
In case frontend and backend are separated, i.e Laravel for backend, Angular for frontend, below are examples for Laravel:
In api.php,
Route::get('teacher-with-students-count', 'TeacherController#getTeacherWithStudentsCount');
In Teacher.php (model)
class Teacher extends Model
{
public function students()
{
return $this->hasMany(Student::class, 'teacher_id', 'id');
}
}
In TeacherController.php
public function getTeacherWithStudentsCount()
{
$teachers = Teacher::where('teacher_status','active')->withCount('students')->get();
return $this->giveSuccessResponse($teachers);
}

Laravel what relation to use in order to see data from another model and column

I have two models
Item:
protected $fillable = [
'code',
'name',
'uom'
];
public function recipe()
{
return $this->belongsTo('App\Recipe');
}
Recipe:
protected $fillable = [
'recipecode',
'itemcode',
'qty'
];
public function item()
{
return $this->hasMany('App\Item');
}
In migration I have:
public function up()
{
Schema::table('recipes', function (Blueprint $table) {
$table->foreign('itemcode')->references('code')->on('items');
});
}
In RecipesController I have:
public function index()
{
$recipes = Recipe::all()->sortBy('recipecode');
$items = Item::all();
return view ('recipe.index', compact('recipes', 'items'));
}
I want to see in the view recipecode, itemcode and ItemName, ItemQty etc.
#foreach($recipes as $recipe)
<tr>
<td>{{ $recipe->recipecode }}</td> // this works
<td>{{ $recipe->itemcode }}</td> // this works
<td>{{ $recipe->item->name }}</td> // this doesn't work
<td>{{ $recipe->item->uom }}</td> // this doesn't work
<td>{{ $recipe->item->qty }}</td> // this doesn't work
</tr>
#endforeach
What should I do in order to see 'name' and 'uom' columns from Items table? I think there is a problem with relations...
First, $recipe->item->name does not work as you expected because $recipe->item is a collection of App\Item, not an App\Item model instance. That's because you have set the relationship to be "hasMany"
Second, please read more about eager loading. What you're doing now are multiple queries. That's the N+1, for each recipe you are querying the database to get the items. You do not need to do that, as it's not performant at all. Use Recipe::with('item')->sortBy('recipecode')->get().
Now, keep in mind that $recipe->item is not a single item, but a collection of items that belong to that Recipe. You'll probably have to work a bit on your table to display multiple items for one Recipe.
Since you are using hasMany you must follow naming convention in naming function
public function items()
{
return $this->hasMany('App\Item');
}
In RecipesController you can eager load.
$recipes = Recipe::with('items')->sortBy('recipecode')->get();
Read documentation here: https://laravel.com/docs/master/eloquent-relationships
Also to show it in your blade
#foreach($recipes as $recipe)
<tr>
<td>{{ $recipe->recipecode }}</td> // this works
<td>{{ $recipe->itemcode }}</td> // this works
#foreach($recipe->items as $item)
<td>{{ $item->name }}</td>
#endforeach
</tr>
#endforeach
Other answers share why you can't directly use $recipe->item. However, I think there is a bigger mistake in database design.
The database that you have designed have a one to many relation. Like, one recipe has a lot of items. However, the reverse one that one item has only one recipe seems wrong. You can cook many recipes with one items. I.E. you can make chicken fry and chicken curry with chicken.
The database design should be something like this,
recipes: code, name, uom
items: code, name
item_recipe: item_code, recipe_code, qty

Relationship one to one laravel 5.2

i try it on this way but not dispalyed the relation
model Admission
public function dossierscocial(){
return $this->hasOne('\App\Dossierscocial');
}
model Dossiersocial
public function admission(){
return $this->belongsTo('\App\Admission');
}
in my view
#if(isset($admission->dossiersocials))
#foreach($admission->dossiersocials as $dossiersocial)
<tr>
<td>{{$dossiersocial->id}}</td>
<td>{{$dossiersocial->user_id}}</td>
<td>{{$dossiersocial->patient_id}}</td>
<td>{{$dossiersocial->admission_id}}</td>
<td>{{$dossiersocial->nationalite}}</td>
</tr>
#endforeach
#endif
because hasOne return single object not collection so you can not use foreach.
there is just one object you can use it like this:
#if(isset($admission->dossiersocials))
<tr>
<td>{{$admission->dossiersocials->id}}</td>
<td>{{$admission->dossiersocials->user_id}}</td>
<td>{{$admission->dossiersocials->patient_id}}</td>
<td>{{$admission->dossiersocials->admission_id}}</td>
<td>{{$admission->dossiersocials->nationalite}}</td>
</tr>
#endif
or maybe you can use hasMany instead of hasOne

Linking to tables and get results through view(blade)

#foreach ($despatchitems as $despatchitem)
<tr>
<td>{{$despatchitem->tag_id}}</td>
<td>{{$despatchitem->qty}}</td>
<td>{{$despatchitem->description}}</td>
</tr>
#endforeach
i need to have the tag name instead of the tag_id, How can i make the connection to Tag table and get the tag name
There is no Direct relationship between DespatchItem Model and Tag Model
You can use the belongsTo relationship in your DespatchItem Model.
public function tags()
{
return $this->belongsTo('App\Tag','tag_id');
}
and Use in your View like below way.
<td>{{$despatchitem->tags->tag_name}}</td>

I am trying to delete a particular record from the table in Laravel 5.3

My view page code is
#foreach($clients as $client)
<tr>
<td>{{ $client->client_id }}</td>
<td>{{ $client->ip_address }}</td>
<td>{{ $client->netmask }}</td>
<td>
<a href= "del/{{$client->id}}"><button type = "button" class = "btn btn-danger ">
Delete
</button>
</td>
</tr>
#endforeach
My controller code for destroy method is :
public function destroy($id)
{
$clients = Subnet_behind_client::findOrFail( $id );
$clients->delete();
return view('view2',compact('clients'));
}
My route file is:
Route::get('del/{id}', 'Subnet_Behind_ClientController#destroy');
I am able to view the records in a table in my view page but I am unable to delete a record from that table.
Your code looks good to me.
By the way, if you are deleting a record using its primary key then you can use destroy()
https://laravel.com/docs/5.3/eloquent#deleting-models
Subnet_behind_client::destroy( $id );
This way you don't need to fetch the record you want to delete. It will optimize the performance a bit.
You're trying to call delete() method onto a collection of records returned from findOrFail() method.
By doing this you can't access the query builder as now you have an Collection instead of a QueryBuilder.
To make it work, you can do it like this:
$clients = Subnet_behind_client::findOrFail( $id )->delete();
return view('view2',compact('clients'));
Hope this helps!
Can you please use this way:
First of all print the data if exist or check for existing entry.
$clients = Subnet_behind_client::where('id', $id)->get();
// dd($clients);
if(count($clients)>0){
Subnet_behind_client::where('id', $id)->delete();
}
I think this trick will help you.
Make sure also if you forgot to mention define top of the controller:
use App\Subnet_behind_client;
This should work:
Subnet_behind_client::destroy( $id );
And for deleting, I would suggest to use DELETE request instead of GET.

Resources