Laravel relationship doesn't return data - php

I am trying to get my data in table by ajax and it's successfull but some of data are id of other tabels and those data i cannot get somehow!
Example
Sample data returned by JS:
customers":[
{
"id":2,
"group_id":3,
"industry_id":2,
"name":"fwgvwrg",
"companyName":"bget"
}
]
In this data if i use like: i.group.name (same as in blade if we say {{$customer->group->name}} for group_id it returns error of
Uncaught TypeError: Cannot read property 'name' of undefined
Basically there is no issue from JS it's about my models relations here are my models:
Customer model
public function group()
{
return $this->belongsTo(GroupCustomer::class, 'id', 'group_id');
}
public function industry()
{
return $this->belongsTo(Industry::class);
}
Groups model
public function customers() {
return $this->hasMany(Customer::class, 'id', 'group_id');
}
Industry model
public function customers() {
return $this->hasMany(Customer::class);
}
Any idea?

Seems the problem is your model relationship about foreign key parameter position:
public function group()
{
return $this->belongsTo(GroupCustomer::class, 'group_id', 'id');
}
See model doc here
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');

In Blade view you can call laravel relationship directly. it will work fine.
but in Js it won't work. you can't call relationship
so when you have to use with() like below
Ex : Customer::with('group')->get();

Related

Retrieving data from hasMany Relationship

I want to show data from 'personas' (parent table) that has at least one 'residente' (child table), its a one to many relationship, and i want to show data of that residente too.
I was trying to do it using the has() method like the laravel documentation says:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
but it does not work.
Models looks like this
//in the Persona class
public function residentes()
{
return $this->hasMany(Residente::class);
}
//in the Residente class
public function persona()
{
return $this->belongsTo(Persona::class);
}
//in the PersonasController
public function index()
{
$personas = Persona::has('residentes')->get();
dd($personas);
}
the Result
enter image description here
//it doesn't get the data from "residentes"
Try :
public function index()
{
$personas = Persona::with('residentes')->get();
dd($personas);
}
If you want to search using some keys inside the residentes relationship you can use whereHas
Persona::with('residentes')
->whereHas('residentes',function($residente){
return $residente->where('column_name',$value);
})->get();
Also try to mention the local_key and the foreign_key in the relationship itself reference : https://laravel.com/docs/9.x/eloquent-relationships
return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
Please try the following in the place of key give actual field names.
//in the Persona class
public function residentes()
{
return $this->hasMany(Residente::class, 'foreign_key', 'local_key');
}
//in the Residente class
public function persona()
{
return $this->belongsTo(Persona::class,'foreign_key', 'owner_key');
}
//in the PersonasController
public function index()
{
$personas = Persona::with('residentes')->get();
foreach($personas as $person){
echo "<pre>";
print_r($person->residentes()->get()->toArray());
}
}

relationship laravel empty result

I´m traying create relation ship in my model user-roles.
Firt i have to say that i´m using Bouncer library to use permission and roles.
I have my model User with this realation:
public function roles()
{
return $this->belongsTo('App\AssignedRoles', 'entity_id');
}
and my model AssignedRole:
public function user()
{
return $this->hasMany('App\User', 'id', 'entity_id');
}
and
public function roleName()
{
return $this->belongsTo('App\Role', 'id', 'role_id');
}
in my controller i´m trayin return all role that it has one User, using this:
$employee = User::with('roles')->get();
but return this:
Array([roles] => )
what i´m doing wrong?
I need create user list with his roles.
Thanks for read and sorry for my english

Unable to seed db table with relationship in Laravel

In a laravel 5.8 application, I want to seed the users & products table. There is a relationship between the users & products like this
User.php model (users can have one or more products)
public function products()
{
return $this->hasMany(Product::class, 'user_id');
}
Product.php model (a product can belong to one or more users)
public function users()
{
return $this->belongsToMany(User::class);
}
I am trying to use the UsersTableSeeder below to seed both the users table & products table at the same time
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->save(factory(App\Product::class, 3)->make());
});
}
and the 'DatabaseSeeder`looks like this
public function run()
{
$this->call(UsersTableSeeder::class);
}
When I run the command php artisan db:seed, only the users table is seeded and I get this error
Symfony\Component\Debug\Exception\FatalThrowableError : Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Database\Eloquent\Collection given, called in C:\Users\Elomena\Projects\Clients\Pramopro\database\seeds\UsersTableSeeder.php on line 15
This is line 15 $user->products()->save(factory(App\Product::class, 3)->make());
I really don't understand why I am getting this error as I have followed the exact thing from the https://laravel.com/docs/5.8/seeding#using-model-factories
Please how should seeding with relationships be done?
This can be solve your problem:
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->saveMany(factory(App\Product::class, 3)->create());
});
}
The error message suggests that you're using a collection instead of a model.
The error is caused by this function, it returns a collection and not a model, because it's a hasMany relationship.
public function products()
{
return $this->hasMany(Product::class, 'user_id');
}
So, you should change your seeder to saveMany instead of save.
public function run()
{
factory(App\User::class, 3)->create()->each(function ($user) {
$user->products()->saveMany(factory(App\Product::class, 3)->create());
}); // ^ saveMany instead of save
}

Laravel Nova nested relation

Recently I've been trying to create Nova resource which depends on the other resource which provides the information for the main resource.
I have a table contest_entries which has the following fields:
id
contest_id
user_id
with the following relations
public function contest() : BelongsTo {
return $this->belongsTo(Contest::class, 'contest_id', 'id');
}
public function user() : BelongsTo {
return $this->belongsTo(User::class, 'user_id', 'id');
}
Also, i have a table contest_submissions with the following fields:
id
entry_id
task_id
comment
approved
declined
with the following relations:
public function entry() : BelongsTo {
return $this->belongsTo(ContestEntry::class, 'entry_id', 'id');
}
public function user() : BelongsTo {
return $this->entry->user();
}
public function contest() : BelongsTo {
return $this->entry->contest();
}
public function task() : BelongsTo {
return $this->belongsTo(Task::class, 'task_id', 'id');
}
I have no problem in fetching this data on the index and details view of Nova, everything 'just works', however, when I try to update the resource, I'm getting the error that user() or contest() is called on null.
I've tried the following,
return [
BelongsTo::make('Contest', 'contest', Contests::class)->exceptOnForms(),
BelongsTo::make('Task', 'task', ContestTasks::class)->exceptOnForms(),
BelongsTo::make('User', 'user', AccountUsers::class)->exceptOnForms(),
]
But for some reason, Nova is still trying to fetch these relationships ever when i explicitly tell it not to.
Any ideas are greatly appreciated, because it works everywhere, except on the update view (create view is explicitly disabled since the submissions are created by the user on the frontend)
You should also chain a hideWhenUpdating() constraint to it.
return [
BelongsTo::make('Contest', 'contest', Contests::class)
->hideWhenUpdating()
->exceptOnForms(),
BelongsTo::make('Task', 'task', ContestTasks::class)
->hideWhenUpdating()
->exceptOnForms(),
BelongsTo::make('User', 'user', AccountUsers::class)
->hideWhenUpdating()
->exceptOnForms(),
]

Laravel many many relation cannot get pivot table

I have laravel's basic auth system, a custom model called SecurityQuestion and a pivot table called securityquestion_user
User
public function securityquestion_user() {
return $this->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
SomeController
First option
foreach(Auth::user()->securityquestion_user as $question) {
dd($question);
}
Error: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$pivot
Second Option
foreach(Auth::user()->securityquestion_user() as $question) {
dd($question);
}
Error: returns false
Ok guys I got it,
I modified the relation to this:
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion', 'securityquestion_user', 'user_id', 'question_id')->withPivot('question_id', 'user_id', 'answer');
}
Basically I reversed the order and place 'user_id' parameter before 'question_id' parameter.
foreach(Auth::user()->securityquestion_user as $question) {
print '<pre>';
print_r($question->pivot->answer);
print '</pre>';
}
Thank you very much for you interest.
Have you added namespace for auth in controller?
Like:
use Auth;
If not imported then use this for it:
foreach(\Auth::user()->securityquestion_user as $question) {
dd($question);
}
And also correct your function in user model
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion::class', 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
because your first option is correct except it!!
Try by using hasMany instead of belongsToMany in user model
public function securityquestion_user() {
return $this->hasMany (SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
Try like this, withPivot function expects one parameter: array or string.
public function securityquestion_user() {
return $this
->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')
->withPivot(['question_id', 'user_id', 'answer']);
}
And 'question_id' and 'user_id' are not necessary to be in withPivot function, since they are the foreign keys.

Categories