How to Sharing or access a relations of intermediate model - laravel

I have a User Model
class User extends Authenticatable
{
public function banks() //this the relation to banks
{
return $this->belongsToMany(Bank ::class, 'customers', 'user_id', 'bank_id')
->withTimestamps();
}
}
and Bank model is
class Bank extends Model
{
public function customers()
{
return $this->belongsToMany(User::class, 'customers', 'bank_id', 'user_id')
->withPivot('name', 'phone', 'state');
}
}
the intermediate model is Customer
class Customer extends Model
{
use HasFactory;
protected $table = 'customers';
protected $fillable = [
//'id' this is the primary key
'bank_id',
'user_id',
'name',
'phone',
'state',
];
public function acounts()
{
return $this->hasMany(Account::class, 'customers_id');
}
}
the Account model is
class Account extends Model
{
use HasFactory;
protected $table = 'accounts';
protected $fillable = [
'customer_id', // this is a foriegin key to customers table
'currency_id',
'balance',
'state',
];
public function accountCurrency() // Accounts
{
return $this->belongsTo(Currency::class, 'currency_id');
}
}
the question is how can access to "acounts" relation from user "banks" what is the statment to link account relation with banks relation
$user = Auth::user();
in view
#foreach ($user->banks as $bnk)
<p class="lead">{{ $bnk->bank_name }} </p>
#foreach ($bnk->accounts as $ account)
<p class="lead">{{ $account->balance }} </p>
<p class="lead">{{ $account->accountCurrency->symbol }} </p>
#endforeach
#endforeach
I hope you help me
thanks

you can use hasManyThrough, check the documentation: https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

Related

Trying to access array offset on value of type null in eloquent Polymorphic

class Product extends Model
{
use HasFactory;
protected $fillable = [
'productName',
'quantity',
'weight',
'boxes',
'MRP',
'costprice',
'productDescription',
'seller_id',
'category_id'
];
public function image()
{
return $this->morphOne(Image::class,'imageable');
}
}
class Image extends Model
{
use HasFactory;
protected $fillable = [
'url',
'size',
'filename',
'imageable_id',
'imageable_type',
];
public function imageable()
{
return $this->morphTo();
}
}
class ProductController extends Controller
{
function index()
{
$product = Product::with('image')->get();
return view('layouts.ecommerce.productAvailable', compact('product'));
}
}
<!---------productAvailable.blade.php--------------
#foreach($product as $key => $val)
<td>{{ $val['image']['id'] }}</td>
#endforeach
i am unable to traverse through relation but when i am using $val['image'] it is returning a collection
#foreach($product as $key => $val)
<td>{{ $val['image'] }}</td>
#endforeach
{"id":3,"imageable_id":14,"imageable_type":"App\\Models\\Product","url":"images\/j1zRX7Cs1DaWFWc1hIi9c17A7Pzj9G7tUMdj576q.jpg","size":"51313","filename":"1643628568.blacky.jpg","created_at":"2022-01-31T11:29:29.000000Z","updated_at":"2022-01-31T11:29:29.000000Z"}
{"id":4,"imageable_id":24,"imageable_type":"App\\Models\\Product","url":"images\/Dz05JmPPuGFSFOO2U1gcb2LJHAz7H63BLGZtPWdQ.jpg","size":"281910","filename":"1643629631.starlet.jpg","created_at":"2022-01-31T11:47:11.000000Z","updated_at":"2022-01-31T11:47:11.000000Z"}
{"id":5,"imageable_id":26,"imageable_type":"App\\Models\\Product","url":"images\/vDdYJKfhy3vzHnfJmxBWA7H8qY1M6Ph9ccfBmc0X.jpg","size":"80911","filename":"1643629652.chuhiya3.jpg","created_at":"2022-01-31T11:47:32.000000Z","updated_at":"2022-01-31T11:47:32.000000Z"}

Favorite functionality for my laravel application

I'm currently trying to make a favorite functionality to my laravel application. I'm trying to access the post table with eloquent, but it says property posts(the function in the favorite model) does not exist.
Update: I updated the query. If I dump $favorite I get two items, which is correct, but now I get this error message instead:Property [posts] does not exist on the Eloquent builder instance. (View: C:\xampp\laravelprojects\Skakahand\resources\views\profile\index.blade.php)
<div class="favorite-section">
<p>Mina favoriter</p>
{{$favorite->posts->title}}
</div>
This is my controller:
public function index(User $user)
{
$favorite = Favorite::where('user_id', auth()->user()->id)
->get();
return view('profile.index',[
'user' => $user,
'favorite' => $favorite
]);
}
Favorite model:
class Favorite extends Model
{
use HasFactory;
protected $fillable = [
'user_id'
];
public function users()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->belongsTo(Post::class);
}
}
and post model:
class Post extends Model
{
use HasFactory;
/* use Sluggable; */
protected $fillable = [
'title',
'body',
'category',
'decision',
'number',
'place',
'image_path',
'slug',
'price',
'user_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function favorites(){
return $this->hasMany(Favorite::class);
}
}
First correct Model like this
class Favorite extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'post_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}
In controller change code like this for for avoid lazy loads
public function index(User $user)
{
$favorites = Favorite::where('user_id', auth()->user()->id)
->with('post')
->get();
return view('profile.index',[
'user' => $user,
'favorites' => $favorites
]);
}
in blade use code like
<div class="favorite-section">
<p>Mina favoriter</p>
<ul>
#foreach($favorites as $favorite)
<li>{{ $favorite->post->title ?? '' }} </li>
#endforeach
</ul>
</div>
just include ->with() for relationship,
your query should look like this
$favorite = Favorite::where('user_id', auth()->user()->id)->with('post')
->get();
return view('profile.index',compact('favorite','user'));

table data relation is not entered, encountered an error Method Illuminate \ Database \ Eloquent \ Collection :: links does not exist

Ticket.php
Protected $table = 'tickets';
Protected $fillable = ['user_id','kategori_id','judul','prioritas_id','status_id','message','file_tambahan'];
public function user()
{
return $this->belongsTo(User::class);
}
User.php
protected $table = 'users';
protected $fillable = [
'avatar','nama_lengkap', 'email', 'password',
];
public function getAvatar()
{
if(!$this->avatar)
{
return asset('images/default.png');
}
return asset('images/'.$this->avatar);
}
public function ticket()
{
return $this->hasMany(Ticket::class);
}
TicketController.php
use App\Model\Ticket;
use App\Model\User;
use App\Model\Kategori;
use App\Model\Prioritas;
use App\Model\Status;
class TicketController extends Controller
{
public function index()
{
$data = Ticket::with('User','Kategori','Prioritas','Status')->get();
return view('admin.crud_ticket.index', compact('data'));
}
index.blade.php
#foreach($data as $d)
<tr role="row" class="odd">
<td>{{ $d->user->nama_lengkap }}</td>
</tr>
#endforeach
{{ $data->links('vendor.pagination.custom') }}
I keep getting the same error over and over again, I do relationships between tables
namely in the user table, category, priority, status.
and cause an error like this, if you have a solution please help me
Method Illuminate\Database\Eloquent\Collection::links does not exist. (View: C:\xampp\htdocs\Helpdesk\resources\views\admin\crud_ticket\index.blade.php)

Trying to get property 'user_nicename' of non-object

I make many database applications, in my database have the same table name and the same file. how can i display all the data
this is my model
this ins my model users
class Users extends Model
{
// protected $connection = 'mysql4';
protected $table = ('ilkom_akbar.table_users');
protected $primaryKey = 'ID';
protected $fillable = [
'ID',
'user_login',
'user_pass',
'user_nicename',
'user_email',
'url',
'user_registered',
'user_activation_key',
'user_status',
'display_name'
];
public function posts()
{
return $this->hasMany(Posts::class,'post_author');
}
}
this ins my model users1
class Users1 extends Model
{
protected $table = 'ilkom_adeputra.table_users';
protected $primaryKey = 'ID';
protected $fillable = [
'ID',
'user_login',
'user_pass',
'user_nicename',
'user_email',
'url',
'user_registered',
'user_activation_key',
'user_status',
'display_name'
];
public function posts()
{
return $this->hasMany(Posts1::class,'post_author');
}
}
this ins my model posts
class Posts extends Model
{
protected $table = 'ilkom_akbar.table_posts';
protected $primaryKey = 'ID';
protected $fillable = [
'ID',
'post_author',
'post_date',
'post_date_gmt',
'post_content',
'post_title',
'post_excerpt',
'post_status',
'comment_status',
'ping_status',
'post_password',
'post_name',
'to_ping',
'pinged',
'post_modified',
'post_modified_gmt',
'post_content_filtered',
'post_parent',
'guid',
'menu_order',
'post_type',
'post_mime_type',
'comment_count'
];
public function users()
{
return $this->belongsTo(Users::class,'ID');
}
}
this ins my model posts1
class Posts1 extends Model
{
protected $table = 'ilkom_adeputra.table_posts';
protected $primaryKey = 'ID';
protected $fillable = [
'ID',
'post_author',
'post_date',
'post_date_gmt',
'post_content',
'post_title',
'post_excerpt',
'post_status',
'comment_status',
'ping_status',
'post_password',
'post_name',
'to_ping',
'pinged',
'post_modified',
'post_modified_gmt',
'post_content_filtered',
'post_parent',
'guid',
'menu_order',
'post_type',
'post_mime_type',
'comment_count'
];
public function users()
{
return $this->belongsTo(Users1::class,'ID');
}
}
this is get data
#foreach ($karyawan1->posts as $data)
<tr>
<td>{{ $no++}}</td>
<td>{{ $data->post_title}}</td>
<td>{{ $data->post_name}}</td>
<td>{{ $data->post_modified}}</td>
<td>{{ $data->post_modified_gmt}}</td>
#endforeach
i believe the some missing from your relation method. you have to specified the foreign_key and owner_key manually, or laravel will do that automatically the laravel way.
in your model post.
public function users()
{
return $this->belongsTo(Users::class, 'post_author', 'ID');
}
in your model post1
public function users1()
{
return $this->belongsTo(Users1::class, 'post_author', 'ID');
}

Eloquent Model has parent model

I have a Model called User with stuff like name, country and some relationships.
Now I want a Model, e.g. Vendor, having all the same functions and variables as a User including some More stuff
I thought I could to it this was:
class User extends Model implements AuthenticatableContract
{
use Authenticatable; SoftDeletes;
protected $dates = ['deleted_at', 'last_login'];
protected $fillable = [
'name',
'password',
'country',
];
protected $hidden = ['password'];
public function logs()
{
return $this->hasMany('App\Log');
}
}
And the Vendor Model:
class Vendor extends User
{
protected $fillable = [
'description'
];
public function user() {
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany('App\Product', 'vendor_id');
}
The Controller checks the role of the user and loads a user model or a vendor model:
if(Auth::user()->role > 1)
$user = Vendor::where('user_id', Auth::user()->id)->first();
else
$user = Auth::user();
return $user->load('logs');
But the load call fails for a vendor. I was able to join the fields of a user inside a vendor but I also need the functions of it.
The problem was that the logs function checks a field that doesn't exists.
Using this functions works:
public function logs()
{
return $this->hasMany('App\Log', 'user_id', get_called_class() !== get_class() ? 'user_id' : 'id');
}

Resources