Laravel Belongs To Not working - php

this should be quite simple but i don't know what wrong . i have the following migrations .
create_players_table
public function up()
{
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->integer('club_id');
$table->string('first_name');
$table->string('last_name');
$table->double('price', 3, 2);
$table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
$table->timestamps();
});
}
create_clubs_table
public function up()
{
Schema::create('clubs', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('location');
$table->timestamps();
});
}
The relationship is straight forward as one player has one team (One to one) and one team can have many players (One to Many ) . The problem is i want to list all the players with their respective teams but somehow i end up with errors . This is my player model .
class Player extends Model
{
public function club()
{
return $this->belongsTo('App\Club');
}
}
And here is the controller :
public function index()
{
$players=Player::find(1);
echo $players->club()->location;
}
I get this error
ErrorException in TeamController.php line 15: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
Any help will be appreciated...

Your relation is not really a database relation try to make you're relation like this:
public function up()
{
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('club_id');
$table->foreign('club_id')->references('id')->on('clubs');
$table->string('first_name');
$table->string('last_name');
$table->double('price', 3, 2);
$table->enum('position', ['goalkeeper','defender','Midfielder','Striker']);
$table->timestamps();
});
}
https://laravel.com/docs/5.4/migrations#foreign-key-constraints

Player Model
class Player extends Model
{
public function club()
{
return $this->belongsTo('App\Club', 'club_id', 'id');
}
}
Player controller
public function index()
{
$players=Player::find(1);
echo $players->club->location;
}

it should be like this :
$players=Player::with('club')->find(1);
echo $players->club->location;

Try without () in ->club(),
public function index()
{
$players=Player::find(1);
echo $players->club->location;
}
As the error says, it refers to the "BelongsTo" relationship. i.e. Here ->club() returns the relationship object, not the club object. If you want to get the club object call as $players->club->location; .

Related

Laravel: Order a model by "Has One Of Many" relationship

I have a customer model that has many contacts. I defined a relationship to get the most recent contact of the customer using the "Has One Of Many" relationship in Laravel 8:
Models
class Customer extends Model
{
use HasFactory;
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->ofMany('contacted_at', 'max')->withDefault();
}
}
class Contact extends Model
{
use HasFactory;
protected $casts = [
'contacted_at' => 'datetime',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
Migration (contact model)
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->softDeletes();
$table->foreignID('customer_id');
$table->string('type');
$table->dateTime('contacted_at');
});
}
}
In my view, I want to show all customers and order them by their latest contact. However, I can't figure out how to do that.
I tried to achieve it via the join method but then I obviously get various entries per customer.
$query = Customer::select('customers.*', 'contacts.contacted_at as contacted_at')
->join('contacts', 'customers.id', '=', 'contacts.customer_id')
->orderby('contacts.contacted_at')
->with('latestContact')
Knowing Laravel there must be a nice way or helper to achieve this. Any ideas?
I think the cleanest way to do this is by using a subquery join:
$latestContacts = Contact::select('customer_id',DB::raw('max(contacted_at) as latest_contact'))->groupBy('customer_id');
$query = Customer::select('customers.*', 'latest_contacts.latest_contact')
->joinSub($latestContacts, 'latest_contacts', function ($join){
$join->on([['customer.id', 'latest_contacts.customer_id']]);
})
->orderBy('latest_contacts.latest_contact')
->get();
More info: https://laravel.com/docs/8.x/queries#subquery-joins
I suspect there is an issue with your migration, the foreign key constraint is defined like this:
Check the documentation:
https://laravel.com/docs/8.x/migrations#foreign-key-constraints
Method 1: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('consumer_id')->constrained();
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}
Method 2: define foreign key constraint
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->string('type');
$table->dateTime('contacted_at');
$table->timestamps();
$table->softDeletes();
});
}

Laravel 8 relationship of three models which belongs to Parent model

Hello everyone I'm currently working on a laravel project where I have a parent table that has the id's of three tables referenced to it. These table migrations also have their models respectively. Here are the table migrations files respectively:
create_products_table.php
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('product_id', 10);
$table->string('product_name');
$table->string('image');
$table->string('images');
$table->string('product_description');
$table->bigInteger('size_id')->unsigned();
$table->string('color');
$table->string('product_quantity');
$table->string('old_price');
$table->string('discount');
$table->string('product_price');
$table->bigInteger('user_id')->unsigned()->nullable();
$table->bigInteger('category_id')->unsigned();
$table->bigInteger('gender_id')->unsigned();
$table->timestamps();
$table->foreign('size_id')->references('id')->on('sizes')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('genders')->onDelete('cascade');
});
create_genders_table.php
Schema::create('genders', function (Blueprint $table) {
$table->id();
$table->string('gender_class');
$table->timestamps();
});
create_categories_table.php
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('cat_name');
$table->timestamps();
});
create_sizes_table.php
Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('sizes');
$table->timestamps();
});
Also this is how I defined the relationships on their models respectively
Product.php
public function category()
{
return $this->belongsTo(Category::class);
}
public function gender()
{
return $this->belongsTo(Gender::class);
}
public function size()
{
return $this->belongsTo(Size::class);
}
Category.php
public function products()
{
return $this->hasMany(Product::class);
}
Gender.php
public function products()
{
return $this->hasMany(Product::class);
}
Size.php
public function products()
{
return $this->hasMany(Product::class);
}
I'm actually a laravel beginner and I studied eloquent model relationships at laravel.com so what I did was just based on my understanding of one to many relationships. When I check all my request with dd($request), category_id, gender_id, size_id all show null and I believe it's because I didn't define the relationship properly. Now this is where I seriously need your assistance.
So please my experienced developers I seriously need your help I'll really be grateful if I get your replies today. Thanks in advance.
=>Everything is right, just make changes in the products migration add this code.
$table->foreign('size_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('gender_id')->references('id')->on('products')->onDelete('cascade');
=>and migrate table

How to store data in one to many relations in laravel?

I want to enter some data from another table and save it in a table. I try to use relationship one to many, but I'm confused to save data
This is my database
public function up()
{
Schema::create('jenis_analisas', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('jenis_analisa', 100);
$table->unsignedBigInteger('kategori_id')->nullable();
$table->integer('harga');
$table->timestamps();
$table->foreign('kategori_id')->references('id')->on('kategoris');
});
}
public function up()
{
Schema::create('permintaan_analisas', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('pelanggan_id');
$table->string('judul_penelitian', 100);
$table->string('jenis_contoh', 50);
$table->string('jumlah_contoh');
$table->string('asal_contoh', 200);
$table->unsignedBigInteger('jenisanalisa_id')->nullable();
$table->timestamps();
$table->foreign('pelanggan_id')->references('id')->on('pelanggans');
$table->foreign('jenisanalisa_id')->references('id')->on('jenis_analisas');
});
}
This is my model
class JenisAnalisa extends Model
{
public function kategori()
{
return $this->belongsTo('App\Kategori');
}
public function permintaananalisa()
{
return $this->hasMany('App\PermintaanAnalisa');
}
}
class PermintaanAnalisa extends Model
{
public function jenisanalisa()
{
return $this->belongsTo('App\JenisAnalisa');
}
}
I want to insert multiple data from jenis_analisas table into permintaan_analisas table.

set where for foriegn table in laravel relation

I have a table has many relation to other tables but it seperated with entity value please look at this :
i have this schema
public function up()
{
Schema::create('cards', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('entity_id');
$table->string('entity');
$table->integer('qty')->nullable()->default('1');
});
}
public function up()
{
Schema::create('tickets', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->string('summary');
$table->integer('amount');
$table->integer('stock')->default('0');
$table->integer('discount')->default('0');
});
}
public function up()
{
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('title');
$table->integer('amount');
$table->integer('discount');
$table->text('description');
$table->integer('stock')->default('0');
});
}
and this relation in models
class Card extends Model
{
protected $table = 'cards';
public $timestamps = true;
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
public function product()
{
return $this->belongsTo('App\Models\Product', 'entity_id');
}
}
i need to set where entity = 'ticket' before use belongsTo i mean is a table hase relation to many table base entity_id and i seperated it by entity column and base same vlue most have realation just.
You can do simply in your eloquent model file. do like this :
public function ticketWithCondition()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id')->where('entity' , 'ticket');
}
public function ticket()
{
return $this->belongsTo('App\Models\Ticket', 'entity_id');
}
call like this :
// for show Card with EntityCondition
$comments = Card::find(123)->with('ticketWithCondition');
// for show comments without EntityCondition
$comments = Card::find(123)->with('ticket');

How to query pivot table using Eloquent in Laravel 5

I have a many-to-many relationship between my client and tag tables. A client can have many tags, and each tag can be related to multiple clients.
On the client show view, I'm trying to display the client info plus all tags associated to this client.
How do I change the query below to retrieve the client rows with all its related tags?
public function show($id)
{
$client = Client::findOrFail($id);
return view('clients.show')->with(['client' => $client]);
}
Client model
public function clienttag()
{
return $this->belongsToMany('App\Clienttag');
}
Clienttag model
public function client()
{
return $this->belongsToMany('App\Client');
}
Client_clientags table migration
public function up()
{
Schema::create('client_clienttag', function(Blueprint $table)
{
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->integer('clienttag_id')->unsigned();
$table->foreign('clienttag_id')->references('id')->on('clienttags')->onDelete('cascade');
$table->timestamps();
});
}
Clients table migration
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->rememberToken();
$table->timestamps();
});
}
Clienttags table migration
public function up()
{
Schema::create('clienttags', function(Blueprint $table)
{
$table->increments('id');
$table->string('tag');
$table->text('description');
$table->rememberToken();
$table->timestamps();
});
}
You can use "Eager Loading" methods like the following
public function show($id)
{
$client = Client::with('clienttag')->findOrFail($id);
return view('clients.show')->with(['client' => $client]);
}
Check documentation at http://laravel.com/docs/5.1/eloquent-relationships#eager-loading
Then at your view you can print your tags
#foreach ($client->clienttag as $tag)
{!! $tag->tagname!!} (or whatever your field in clienttags table name is)
#endforeach

Categories