Unable to use `lists` in many to many relationship - php

My Laravel version is 5.5.13.
I created a many to many relationship between User model and Pet model. Pets can belong to multiple users.
I am trying to do in my update method in controller, get a list of all associated user ids. So I tried:
public function update(Request $request, Pet $pet)
{
dd($pet->users()->lists('id'));
$pet->update($request->all());
return response()->json($pet, 200);
}
However I get:
Call to undefined method Illuminate\Database\Query\Builder::lists()
It seems there is no lists().
If I do dd($pet->users()) it gives no error and shows a lot of information.
*May you please help to get this lists() to work.
My relationship in Pet model is:
public function users()
{
return $this->belongsToMany('App\User');
}
And my relatinship in User model is:
public function pets()
{
return $this->belongsToMany('App\Pet');
}
Here is my migration for the pivot:
Schema::create('pet_user', function (Blueprint $table) {
$table->integer('pet_id')->unsigned()->index();
$table->foreign('pet_id')->references('id')->on('pets')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});

list() is no more available in Laravel. Alternatively you can use pluck() and pluck all items like this pluck()->all();
pluck('key')->all();
pluck()->all();
Reference doc

laravel has deprecated the lists() method use pluck instead.
https://laracasts.com/discuss/channels/laravel/lists-deprecated-replacement

Related

getting notifiable and implementing custom morph relation in Laravel notification

I want to get the notifiable model relation while getting notifications for a specific user. And plus I want to save and get custom morph relation (i.e. causer (causer_id and causer_type)) in notification table (just like notifiable). I was able to create a morph relation and saving it into table record but I am having trouble while getting the relation model, it returns null in both relations. Sharing the code.
custom DatabaseChannel -- the modified buildPayload method.
protected function buildPayload($notifiable, Notification $notification)
{
$data = $this->getData($notifiable, $notification);
$causer = $data['causer'];
unset($data['causer']);
return [
// README: removed uuid from here
'type' => method_exists($notification, 'databaseType')
? $notification->databaseType($notifiable)
: get_class($notification),
'data' => $data,
'read_at' => null,
'causer_type' => get_class($causer),
'causer_id' => $causer->id,
];
}
custom notifiable trait
use Illuminate\Notifications\Notifiable as BaseNotifiable;
trait Notifiable
{
use BaseNotifiable;
/**
* Get the entity's notifications.
*/
public function notifications(): MorphMany
{
return $this->morphMany(Notification::class, 'notifiable')
->orderBy('created_at', 'desc');
}
}
and one thing more I'd like to ask here, how can I refer to two morph relations to single table, like I want to add notifications method with causer and as well as notifiable.
custom Notifications Model
class Notification extends DatabaseNotification
{
public function causer()
{
return $this->morphTo();
}
}
what I am missing or doing wrong? Is it even possible what I am trying to do?
In order to get morph relation (one or maybe two), you need to select columns {morph}_id and {morph}_type, this is just in case if you are using ->select() while getting records, if you are not using select, that'd not be doing any issue.
EDIT
Here is how you add custom columns to notifications table
public function up()
{
Schema::table('notifications', function (Blueprint $table) {
$table->string("causer_type")->after('notifiable_id');
$table->unsignedInteger("causer_id")->after('causer_type');
$table->index(["causer_type", "causer_id"]);
});
}
public function down()
{
Schema::table('notifications', function (Blueprint $table) {
$table->dropMorphs('causer');
});
}

One to Many Relationship Laravel cannot display the related data

I have two models called DataKelurahan and RegistrasiPasien and have a one-to-many relationship, but I can't access the relationship.
I have made a form for adding patient and save it to the registrasi_pasiens table and it works well. but when I try to display the relation data, it doesn't work properly.
In the registrasi_pasiens table, I have 1 record with kelurahan_id = 3. Then, I try to access it via php artisan tinker with these command:
$kelurahan = App\Domain\DataKelurahan\Models\DataKelurahan::find(3) works fine and data is exist.
$pasien = App\Domain\RegistrasiPasien\Models\RegistrasiPasien::find(2007000001) works fine and the data is exist with kelurahan_id = 3
$kelurahan->pasiens the result is null. Shouldn't it show the pasien data that has kelurahan_id = 3?
$kelurahan->pasiens->nama and the result is like this PHP Notice: Trying to get property 'nama' of non-object in D:/PROFESSIONAL/PROJECT/WEB DEVSeval()'d code on line 1 => null
I don't have any idea what's wrong with my codes. Much appreciate for your help guys.
Below are the models that I have made:
DataKelurahan.php
<?php
namespace App\Domain\DataKelurahan\Models;
use Illuminate\Database\Eloquent\Model;
use App\Domain\RegistrasiPasien\Models\RegistrasiPasien;
class DataKelurahan extends Model
{
protected $fillable = ['nama_kelurahan', 'nama_kecamatan','nama_kota'];
public function pasiens(){
return $this->hasMany('RegistrasiPasien');
}
}
RegistrasiPasien.php
<?php
namespace App\Domain\RegistrasiPasien\Models;
use Illuminate\Database\Eloquent\Model;
use App\Domain\DataKelurahan\Models\DataKelurahan;
class RegistrasiPasien extends Model
{
protected $fillable = [
'nama',
'alamat',
'telepon',
'rt',
'rw',
'tgl_lahir',
'jenis_kelamin'
];
public function kelurahan(){
return $this->belongsTo('DataKelurahan');
}
}
And below are my database tables:
data_kelurahans
Schema::create('data_kelurahans', function (Blueprint $table) {
$table->increments('id');
$table->string('nama_kelurahan');
$table->string('nama_kecamatan');
$table->string('nama_kota');
$table->timestamps();
});
registrasi_pasiens
Schema::create('registrasi_pasiens', function (Blueprint $table) {
$table->increments('id');
$table->integer('kelurahan_id')->unsigned();
$table->string('nama');
$table->string('alamat');
$table->char('telepon', 15);
$table->integer('rt');
$table->integer('rw');
$table->date('tgl_lahir');
$table->string('jenis_kelamin');
$table->timestamps();
});
Schema::table('registrasi_pasiens', function (Blueprint $table){
$table->foreign('kelurahan_id')->references('id')->on('data_kelurahans')->onDelete('cascade');
});
From Docs:
Eloquent will automatically determine the proper foreign key column on
the model. By convention, Eloquent will take the "snake case"
name of the owning model and suffix it with _id.
So, Eloquent probably got your foreign key name wrong so you must override the foreign key by passing additional arguments to the hasMany/belongsTo method:
public function pasiens(){
return $this->hasMany('RegistrasiPasien','kelurahan_id');
}
public function kelurahan(){
return $this->belongsTo('DataKelurahan','kelurahan_id');
}

Is ti posible to get value name from related table this way

Ok so I need to get data from the table this way but I would like to get
Vehicle Maker name too
I tried using join or
just doing auth()->user()->vehicles->VehicleMaker but it doesn't work
Migration of Table Vehicle
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id');
$table->bigInteger('category_id');
$table->bigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
Migration of vehicle_makers
Schema::create('vehicle_makers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Controller
public function show(){
$vehicles = auth()->user()->vehicles; -- what shoul i add here
return view('/home', [
'vehicles' => $vehicles
]);
}
Edit
I forget to mention that I already made a relationship and they work in artisan tinker when I try to do something like this:
Vehicles->find(1)->VehicleMaker
What I want is to do is
auth()->user()->vehicles and get vehicle teble with vahicle_maker name not id so some kind of join that would work in this case
Okay base on Laravel Model Relationship.
You first need to create a migration.
Vihicle Migration
Schema::create('vehicles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('vehicle_maker_id');
$table->string('name');
$table->double('price', 8 , 2);
$table->year('manufacture_year');
$table->bigInteger('mileage');
$table->string('vehicle_image');
$table->boolean('admin_verification')->nullable();
$table->timestamps();
});
I used unisignedBigInteger to determine it is a foreign key or you can also use index().
In your model you should place what relation ship you will use. In your case I assumed you are using One To Many Relationship. So that your user model should look like this:
User Model
...
public function vehicles() {
return $this->hasMany(Vehicle::class);
}
So that you can use the convention auth()->user()->vehicles;.
Note: the auth()->user()->vehicles; return a array of object you can loop it in foreach.
Vehicle Model
public function user() {
return $this->belongsTo(User::class);
}
In when you have this in your model you can use it 2 way.
In your controller you can call the relationship of those 2.
Controller
$vehicles = auth()->user()->vehicles;
dd($vehicles);
INFO
You can also refer to this tutorial.
EDIT
Controller
$vehicles = auth()->user()->vehicles();
foreach($vehicles as $vehicle) {
dd($vehicle->VehicleMaker);
}
Note: The $vehicles is returning an array of object. So you can loop it through foreach loop to throw a single instance.
There should be a relationship between the user and vehicles then another relationship between vehicles and vehicle_makers. If you already created your models(Vehicle, VehicleMaker) with their migrations, You can do the following
//add this to your User model.
public function vehicle(){
return this->belongsTo(App\Vehicle);
}
// add this to your Vehicle model
public function user(){
return this->hasMany(App\Vehicle); // implying that a user can have many vehicles
}
//add this to your vehicleMaker model
public function vehicle(){
return this->belongsTo(App\Vehicle);
}
When that is done, you can use Laravel's lazy loading to fetch relationships. You can do something like
$vehicles = auth()->user()->vehicle
return view('/home', [
'vehicles' => $vehicles
]);

laravel eloquent relations doesn't work

I am new to laravel. I am trying to build a relationship between two tables.
my database tables
comments table
$table->increments('id');
$table->text('comment');
$table->string('shop_name','80');
$table->bigInteger('product_id');
$table->timestamps();
comments_images table
$table->increments('id');
$table->bigInteger('comment_id');
$table->string('images','255');
$table->string('shop_name','80');
$table->timestamps();
=========================
Comment model
public function images()
{
return $this->hasMany(Comments_images::class,'comment_id');
}
Comments_images model
public function comments()
{
return $this->belongsTo(Comment::class);
}
I tried to return related data like this
return Comments_images::find(439)->comments()->get();
return Comment::find(880)->images()->get();
return (new Comment())->images()->get();
None of them work!
What should I do?
Are you utilizing the namespace correctly? For example, 'App\Comments_images'.. Also, models are best left singular- for example, 'Comment' or 'Comment_Image'. I bring that up because you aren't being consistent, which may be causing the error. The last thing is to use a string of the class, not returning an actual class. See the below examples, and notice capitalization and that I don't put an 's' on some things..
// in Comment model
public function images()
{
return $this->hasMany('App\Comments_Image','comment_id');
}
// in Comments_Image model
public function comment()
{
return $this->belongsTo('App\Comment', 'id', 'comment_id');
}
Edit: Feel free to use Comment::class instead of the string 'App\Comment' - It resolves to the same thing and works better with editor navigation, autocomplete, and other helpful things.

unable to get attributes in an accessor method - laravel eloquent

Okay I want to have custom field that does not exist as a column in my db table.
I followed, last part :
http://laravel.com/docs/4.2/eloquent#accessors-and-mutators
My model code:
class Car extends Eloquent{
protected $fillable = array('driverID', 'fuelRemaining');
protected $appends = array('is_driver');
public function user(){
return $this->belongsTo('user');
}
public function getIsDriverAttribute(){
return ($this->attributes['driverID'] == Auth::user()->id);
}
}
Car table:
Schema::create('cars', function(Blueprint $table)
{
$table->increments('id');
$table->integer('driverID');
$table->integer('fuelRemaining');
$table->mediumtext('desc');
$table->timestamps();
});
As you can see i want an extra field which is "is_driver" to be returned, but when I run this, this field is used to determine whether current signed in user is the driver himself by comparing the IDs.
it will output this error:
Undefined index: driverID
Not sure what am I doing wrong here, please advice.
Ah I have found why. This is a reference for future readers
In my controller I only get these two
$car = Car::where('fuelRemaining', 0)->get(array('id', 'desc'));
When i added authorID to the get array
$car = Car::where('fuelRemaining', 0)->get(array('id', 'desc', 'authorID'));
I am able to get the authorID attribute in my custom accessor mentioned in the question.

Categories