Primary Key and Foreign Key on Laravel - php

I know this questions already are asked but I am stuck...
I have 2 tables (clubs and membres):
In my table clubs I have 3 fields id_club, name_club, type_sport_club
Everything is working on my table Clubs
However I am stuck in my table Membres, I don't understand...
My problem is I only get number of my fk and no the name of club...
For information I have 3 fields id_membre, name_membre, fk_club
So...In my database I have this
public function up()
{
Schema::create('membres', function (Blueprint $table) {
$table->increments('id_membre');
$table->string('name_membre');
$table->integer('fk_club')->unsigned();
$table->foreign('fk_club')->references('id_client')->on('clients');
$table->timestamps();
});
}
Then on Model I have this
class Membre extends Model
{
//
protected $fillable = ['name_membre', 'fk_club'];
}
After for Controller I have this
public function index()
{
$membres = Membre::oldest()->paginate(5);
return view('admin.membres.index', compact('membres'))
->with('i', (request()->input('page', 1)-1)*5);
}
In my index.blade I have this
#foreach($membres as $membre)
<tr>
<td> {{$membre->name_membre}}</td>
<td> {{$membre->fk_club}}</td>
<td>
<form method="POST" action="{{ route('membres.destroy', $membre) }} ">
<a class="btn btn-sm btn-warning" href="{{route('membres.edit',$membre->id_membre)}}">Editer</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Deleter</button>
</form>
</td>
</tr>
#endforeach
Thank you for your help.

On your Membre Model Add this
class Membre extends Model{
//
protected $fillable = ['name_membre', 'fk_club'];
public function club(){
return $this->belongsTo('App\Club', 'fk_club');
}
}
You can get this data on your view file by
<td> {{$membre->club->name_club}}</td>
And your Club Model add this
class Club extends Model{
public function membre(){
return $this->hasMany('App\Membre', 'fk_club','id_club');
}
}

First of all, your foreign key in the members migration references id_client in the clients table, you probably want that to reference id_club in the clubs table (unless your table is actually called clients).
Then to get the name of the club a member belongs to, you'll have to add a function called club to your Membre model, which returns something like $this->belongsTo('App\Club');. If you haven't done so, you should also add a members function to your Club model, which returns something like $this->hasMany('App\Membre');.
In your view you can access the name of the club with $membre->club->name_club.
Here's a link to the Laravel documentation about Eloquent relationships, maybe that helps clearing things up.

You need to define your relation,
class Membre extends Model
{
//
protected $fillable = ['name_membre', 'fk_club'];
public function club()
{
return $this->belongsTo('App\Club', 'fk_club');
}
}
Now you can use this like below,
<td> {{$membre->club->name_club}}</td>

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

Laravel 7 : trying to get the name instead of id

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.

How to show 'name' column of table instead of id in Laravel

I have three tables; Income, Expenses and IncomeExpenses. IncomeExpenses contains foreign keys of both Income and Expenses.
class IncomeExpenses extends Model
{
public function income(){
return $this->belongsTo(Income::class);
}
public function expense(){
return $this->belongsTo(Expenses::class);
}
}
Also, IncomeId and ExpensesId are used in view and I use dropdownlists for them and what I want to achieve is that after I add new record with those dropdownlists I want to show title of IncomeId or ExpensesId instead of id. Yes I know it is better to use eager loading but I do not know how to achieve it.
Controller:
public function show($id)
{
$incexp = IncomeExpenses::find($id);
$income=IncomeExpenses::with('income')->get();
return view('incomeExpense.show', compact('incexp','income'));
}
Income model:
class Income extends Model
{
//
}
Expenses model
class Expenses extends Model
{
//
}
View:
<div class="card bg-muted">
<h1>{{$incexp->IncomeExpense}}</h1>
<small>Added at {{$incexp->created_at}}</small>
<small> Type of Income:{{$income->income->title}}</small>
<small> Money:{{$incexp->SumOfMoney}}</small>
<small> Comments:{{$incexp->Comments}}</small>
<small> Type of Expenses:{{$incexp->ExpenseId}}</small>
</div>

Relationship with Pivot Table Laravel's Eloquent and Inner Loops

Ok, can anyone help me with this scenerio? I want to make a loop of Divisions and an inner loop of all the teams in that division using relationships in Eloquent. Been googling and expermenting but can't get the right results.
My tables are as such:
Divisions
division_id INT PK
division_name VARCHAR
...
Teams
team_id INT PK
team_name VARCHAR
...
division_team (pivot table)
id INT PK
division_id INT FK
team_id INT FK
My Models are as such:
DivisionTeamPivot
class DivisionTeamPivot extends \Eloquent {
protected $fillable = [];
protected $table = 'division_team';
public function team(){
return $this->belongsTo('Team');
}
public function division(){
return $this->belongsTo('Division');
}
Divisons
class Division extends \Eloquent {
protected $primaryKey = 'division_id';
public function teams(){
return $this->hasMany('Team','division_team','division_id','team_id');
}
}
Teams
class Team extends \Eloquent {
protected $primaryKey = 'team_id';
public function division(){
return $this->belongsTo('Division','division_team','team_id','division_id');
}
}
My Controller has:
$divisions = DivisionTeamPivot::with('Team','Division')->get();
My View:
<section class="panel">
<header class="panel-heading">
<h5>{{$division->division->division_name}} Division {{$i}}</h5>
</header>
<table class="table">
<thead>
<tr>
<th></th>
<th>Team Name</th>
<th class="center">Total Points</th>
<th class="center">Rank</th>
</tr>
</thead>
<tbody>
#foreach($division->team as $team)
<tr>
<td width="75"><img src="/img/logos/{{team->team_logo}}" width="50"></td>
<td> {{team->team_name}}</td>
<td class="center">1,345</td>
<td class="center">1</td>
</tr>
#foreach
</tbody>
</table>
</section>
What I want to do is loop over the divisions and then sub loop the teams that are in those divisions. I saw someone on here to make a pivot table model but when I use it, it loops over all the same divisions based off the division_id table in the pivot but I get the name. Its creating one team per duplicate division. I need them grouped based on the divisions they are in. And, actually, I still can't get the teams name to show. I also really want the eager loading to be working so I get the most efficient queries I can. Thanks!!
For making the many-to-many relationship you need to use belongsToMany instead of belongsTo in your both models (Division and Team) and you don't need to use another model as DivisionTeamPivot for pivot table. So in Division and Team use belongsToMany method:
// Division Model
public function teams(){
return $this->belongsToMany('Team', 'division_team', 'division_id', 'team_id');
}
// Team Model
public function divisions(){
return $this->belongsToMany('Division', 'division_team', 'team_id', 'division_id');
}
Make the query like this:
$divisions = Division::with('teams')->get();
return View::make('viewname')->with('dvisions', $divisions);
In the view the nested loops could be something like this:
#foreach($divisions as $division)
{{ $division->division_name }}
#foreach($division->teams as $team)
{{ ... }}
{{ $team->team_name }}
#endforeach
#endforeach

Laravel 4 - Access to Table through Relational Models

Edit: typo
I have two Models: Project and Task. Both are relational to each other:
Project.php
class Project extends Eloquent {
public function tasks()
{
return $this->hasMany('Task');
}
Task.php
class Task extends Eloquent {
protected $guarded = [];
public function project()
{
return $this->belongsTo('Project');
}
Through my ProjectsController I pass the necessary Variables to my Projects View, like this:
ProjectsController:
public function index()
{
$projects = Project::with('tasks')->get();
return View::make('projects.index')
->with('projects', $projects);
}
And in my View I loop through every Project to show everything on a table:
Projects List
<table>
<tr>
<th>Id</th>
<th>Titel</th>
<th>Description</th>
<th>Tasks</th>
</tr>
#foreach($projects as $project)
<tr>
<td>{{$project->id}}</td>
<td>{{$project->title}}</td>
<td>{{$project->description}}</td>
<td>{{$project->task}}</td>
</tr>
#endforeach
</table>
As you can see, the last td-Tag, should access data from the tasks table.
I know that the above View does not work. But I want to know in general, how I would go about it, if I want to output the number of tasks, each project has.
Or anything else, that explains, how I can access different tables, through relational Models, in this particular situation.
since you defined the project model with $this->hasMany('Task'); and fetched models with their tasks, you can simply do
{{ $project->task()->count() }}
be sure to call the tasks as if it were a function, instead of a property.

Categories