Laravel ManyToMany Fail - laravel

i got this function in user model
public function kelas(){
return $this->belongsToMany('App/Kelas','user_classes','id_user','id_class')->withTimeStamps();
}
i got this function in kelas model
public function user(){
return $this->belongsToMany('App/User','user_classes','id_class','id_user');
}
My Controller
public function kelas()
{
$kelas = Kelas::all();
$namaguru = Auth::user()->name;
$idlogin = Auth::user()->id;
$kelasdiambil = User::get();
$kelaspengajar = Kelas::all()->where("namaguru",$namaguru);
return view('crudkelas', compact("kelas","kelaspengajar",'kelasdiambil'));
}
My pivot migration
Schema::create('user_classes', function (Blueprint $table) {
$table->unsignedBigInteger('id_user');
$table->unsignedBigInteger('id_class');
$table->timestamps();
$table->primary(['id_user','id_class']);
$table->foreign('id_user')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('id_class')->references('id')->on('classes')->onDelete('cascade')->onUpdate('cascade');
});
I want to create a view that show all namekelas at classes table using this pivot table with condition where id_user == Auth::user()->id ....
#foreach($kelasdiambil->kelas as $pel)
<tr>
<td>{{$pel->namekelas}}</td>
<td>{{$pel->kode}}</td>
<td>Edit Hapus</td>
</tr>
#endforeach
Error
Property [kelas] does not exist on this collection instance. (View: I:\darinol\nictoschool\resources\views\crudkelas.blade.php)
in english language, i just wanna create a user and class table became manytomany relationship and make a view to show all classname at classes table using this pivot table where the condition is id_user at pivot == Auth::user()->id; :( help me

You have to write like this
public function kelas(){
return $this->belongsToMany('App\Kelas','user_classes','id_user','id_class')->withTimeStamps();
}
public function user(){
return $this->belongsToMany('App\User','user_classes','id_class','id_user');
}
You use collection of array
$kelasdiambil = User::get();
So You have to use like this
#foreach($kelasdiambil as $pel)
<td>{{$pel->kelas->namekelas}</td>
Or you have to use like this
$kelasdiambil = User::first();

Related

Property [countries] does not exist on this collection instance

I am trying to create a drop down menu by with eloquent from where I can go to subcontinent with drop down and subcontinent to countries with sub-dropdown. The relationship is Subcontinent has many countries.
Models
Subcontinent
class Subcontinent extends Model
{
protected $guarded = [];
public function countries()
{
return $this->hasMany(Division::class, 'country_name', 'id');
}
}
Country
class Division extends Model
{
protected $table = 'divisions';
protected $fillable = [
'country_name', 'subcontinent_id'
];
public function subcontinent()
{
return $this->belongsTo(Subcontinent::class, 'country_name', 'id');
}
}
The table name of country is divisions and the model name is also Division.
Table
country/division
Schema::create('divisions', function (Blueprint $table) {
$table->id();
$table->string('country_name');
$table->bigInteger('subcontinent_id');
$table->timestamps();
});
Database formation
$subcontinents = Subcontinent::orderBy('id', 'DESC')->get();
But when I try to call dd($subcontinents->countries) it gives me property does not exist error.
"Property [countries] does not exist on this collection instance."
with $subcontinents = Subcontinent::find(1);
the dd still gives null value. How can I call subcontinents to countries!
you have misconception about second and third option in relationship method. for belongsTo relationship, the second argument is the foreign key of the child table and the third argument is the primary key or the reference key of the parent table.
your Division model relationship should be
public function subcontinent()
{
return $this->belongsTo(Subcontinent::class, 'subcontinent_id', 'id');
}
and for hasMany relationship the second argument is the foreign key in the child table. For SubContinent model the relationship would be
public function countries()
{
return $this->hasMany(Division::class, 'subcontinent_id', 'id');
}
and when you use $subcontinents = Subcontinent::orderBy('id', 'DESC')->get(); you get a collection, not an object. you have to loop over to get values and relationship data from this.
foreach($subcontinents as $subcontinent) {
$subcontinent->$subcontinent_name;
$subcontinent->countries;
}
and when you use $subcontinents = Subcontinent::find(1); you get an object. you can directly access its values. just update the relationship method. and you will get values by $subcontinents->countries then.

Define additional relationship on many-to-many polymorphic relationship

I'm creating an taggable table like so:
Schema::create('taggable', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('tag_id');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->unsignedBigInteger('taggable_id');
$table->string('taggable_type');
$table->unsignedBigInteger('company_id');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->unsignedBigInteger('created_by')->nullable();
$table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
$table->timestamps();
});
As you can see, next to connecting tags to a Post, Video etc (as per the Laravel docs example), I'd also like to ensure that the row that's added is connected to a Company and User model so I can keep track who it belongs to and who created it, but even more so access properties from those models in controllers and views.
I know that in my Post model I can do:
public function tags()
{
return $this->morphedByMany(\App\Models\Tag::class, 'taggable')->withPivot('created_by', 'company_id', 'created_at');
}
The problem is that this will retrieve just the value for created_by and company_id and not the Eloquent model. Is this possible?
So what I'd like to do is access properties of those relationships in controllers and views like so:
$post = Post::findOrFail(1);
foreach($post->tags as $tag) {
$tag->created_by->name // accessing 'name' property on the `User` model
}
foreach($post->tags as $tag) {
$tag->company->address // accessing `address` property on the `Company` model
}
You must do like below:
first you must define relationship between tags and users
class Tags extends Model
{
public function taggable(): MorphTo
{
return $this->morphTo();
}
public function createdBy(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
}
then for achieve that you want you must:
$post = Post::first();
$users = $post->tags()->with('createdBy')->get();

Eloquent 'with()' returns null

I have a simple relationship between two models: User and Prescription. A user has many prescriptions. In the PrescriptionsController, when I try to get the user that the prescriptions belongs to, it returns null when using with().
PrescriptionsController
public function index()
{
$user_id = Auth::id();
$prescriptions = Prescription::with('user')->where('prescription_for', $user_id)->get();
return response()->json($prescriptions);
}
The result from that Eloquent query:
[{"id":1,"prescription_for":1,"prescription_by":1,"prescription_content":"Paracetamol 120mg - O cutie. Mod administrare: 1 Dimineata | 0 Pranz | 0 Seara","created_at":"2020-10-13T17:33:35.000000Z","updated_at":null,"user":null}]
You can see that the last parameter is null.
In my User model, I have set up the relationship using:
public function prescriptions()
{
return $this->hasMany(Prescription::class);
}
And the Prescription model:
protected $table = 'prescriptions';
public $primaryKey = 'id';
public $timestamps = true;
public function user()
{
return $this->belongsTo(User::class);
}
I am using VueJs so I cannot just do $prescription->user->name as you can in Blade files, that's why I need to eager load the data.
The way I set up the Prescriptions table:
$table->id();
$table->unsignedBigInteger('prescription_for');
$table->foreign('prescription_for')->references('id')->on('users');
$table->unsignedBigInteger('prescription_by');
$table->foreign('prescription_by')->references('id')->on('users');
$table->string('prescription_content');
$table->timestamps();
Any ideas to why this happens? Thanks!
On your prescriptions table, your primary key is prescription_for. If the parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo() method specifying the parent table's custom key :
public function user()
{
return $this->belongsTo(User::class, 'id', 'prescription_for');
}

belongsToManyRelation not working in laravel 8

I have many to many relation which is inserting data correctly but when I try to fetch data it gives me no data.
one table is boss and other is workers
Migration
<?php
public function up()
{
Schema::create('boss_worker', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('worker_id');
$table->unsignedBigInteger('boss_id');
$table->timestamps();
});
}
Boss model relation
public function workers()
{
return $this->belongsToMany(\App\Models\Admin\Worker::class,'boss_worker');
}
How I am trying to fetch data
public function index()
{
$boss = Boss::find(1);
dd($boss->workers);
}
How I am inserting data
$input = $request->all();
$workers = $input['workers'];
$input['workers'] = implode(',', $workers);
$boss = Boss::where('staff_id',$request->boss)->first();
$worker_gangs = $boss->workers()->sync($workers);
It is not fetching any data
use
public function index()
{
$boss = Boss::with('workers')->find(1);
}
When you call a relationship from a model you are calling to Illuminate\Database\Eloquent\Builder so, you can access and apply any filter or query with the Query Builder, to fetch the data from that relationship, you have to use these methods to execute the query
->get();
->first();
your code have to be:
$boss = Boss::find(1);
$workers = $boss->workers()->get();
dd($workers);
or you can make eager loading with the Boss model
$boss = Boss::with('workers')->find(1);
dd($boss->workers);

Laravel Eloquent Relationship has the same foreign key on the same table

I'm a beginner in Laravel and currently trying to create a ticketing system. My tickets table has two columns which both reference id from the users table namely user_id and handled_by. I am trying to eager load the full_name of handled_by but it is throwing an error "Trying to get property 'full_name' of non-object". I would like to know how to properly create an eloquent relationship between handled_by and tickets so I could display the handled_by's full_name. Below are snippets of my code.
User Model:
public function tickets(){
return $this->hasMany('\App\Ticket');
}
public function handledBy(){
return $this->hasMany('\App\User', 'handled_by', 'id');
}
Ticket Model:
public function user(){
return $this->belongsTo('\App\User');
}
public function handledBy(){
return $this->belongsTo('\App\User', 'handled_by', 'id');
}
View:
#foreach($tickets as $ticket)
<td class="align-middle text-center">{{ $ticket->handled_by->full_name}}</td>
#endforeach
Controller:
$tickets = Ticket::all()->where('status_id', '1');
return view('admin.open_tickets', compact('tickets'));
In your User model, change \App\User to \App\Ticket, and change the method name from handlerBy to handlers:
public function handlers(){
return $this->hasMany('\App\Ticket', 'handled_by', 'id');
}
And call it by method's name instead of underline case name:
{{ $ticket->handledBy->full_name}}

Resources