the relation is not appending to the model in laravel - php

i want to append a relation to my model in laravel i know its possible with resource but i need it to be appened to model so here its like below what i do :
protected $appends = ['accommodation_rooms'];
public function getAccommodationRoomsAttribute(){
return $this->accommodationRooms();
}
and my relation is :
public function accommodationRooms()
{
return $this->Hasmany(AccommodationRoom::class);
}
but when i run my api it returns null but when i call the relation it has the relation and it has no problem . any idea what i am doing wrong ??
EDIT
$data = Accommodation::with('city', 'accommodationFacilities', 'gallery')
->where('is_deleted', 0)->Paginate(env('PAGINATE_NUMBER'));
return $data;

return $this->accommodationRooms() will return an instance of query builder. That is probably why it was showing empty.
Change it to
public function getAccommodationRoomsAttribute(){
return $this->accommodationRooms;
}

Call it without ()
public function getAccommodationRoomsAttribute(){
return $this->accommodation_rooms;
}
And update your relation to:
public function accommodationRooms()
{
return $this->hasMany(AccommodationRoom::class);
}
And make sure you have accommodation_id column in your accommodation_rooms table

Related

Laravel return model with if statement

I'm trying to create offers and assign them to parent categories, to be more specific i have an Offer model and inside the offer model i have this many to many relationship
public function category() {
return $this->belongsToMany(Category::class);
}
I want the above function to return ONLY the categories which have NULL parent_category which mean they are the parent categories. Is it possible with the above code?
Without knowing the entire scope of your project, I'd suggest one of the following: either change the name of the relation (A) or keep the relation as is and query it when you need it (B).
Option A -
public function childCategory() {
return $this->belongsToMany(Category::class)->whereNull('parent_category');
}
Option B -
public function category() {
return $this->belongsToMany(Category::class);
}
$offer = Offer::with('category')
->whereHas('category' function ($query) {
$query->whereNull('parent_category');
});
public function category() {
return $this->belongsToMany(Category::class)->where('parent_category', null);
}

get null value when return eloquent model relation

I use eloquent package in project (I do not use laravel!!) when I return a model relation , the result is null. But I create relation model !! And in mysql is true
In my book model
public function plandtls()
{
return $this->hasMany('App\Models\plandtls','book_id');
}
and my plandtls
public function book()
{
return $this->belongsTo('App\Models\book','book_id');
}
and execute query :
public function planList()
{
$list = plandtls::select()->with('book')->first();
var_dump($list);
}
Finaly I get null result.
Please help me.

Cache relation laravel with orderby

I would like to know how can I cache laravel relation with orderby in controller ?
Currently I have this in my controller :
MyController.php
$replies = $message->replies()->orderBy('position', 'asc')->get();
MessageEntity.php
/* Message has many Replies */
public function replies() {
return \Cache::remember('messages_' . $this->id . '_replies', $this->expiration, function () {
return $this->hasMany('App\Model\Entities\ReplyEntity', 'fk_message_id', 'id')->get();
});
}
But I have this error :
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::orderBy does not exist.
since you are using get() in your relation method, the method wont return the relation but will return the list from db, and that would make sense, because you don not want to cache the relation, but you want to cache the data:
you may add orderBy clause to your query Builder in the function before using 'get()'
public function replies() {
return \Cache::remember('messages_' . $this->id . '_replies', $this->expiration, function () {
return $this->hasMany('App\Model\Entities\ReplyEntity', 'fk_message_id', 'id')->orderBy('position', 'asc')->get();
});
}
please not if your order by columns or direction are not always the same, you should include the order direction and columns in the key of you cache
as a personal opinion, the relation method should represent the relation only, without get and cache, so you can use it somewhere else.
the cache should be in the repository of the model ('MessagesRepository')
It is because of you are retrieving a collection and the orderBy() is a query method.
You will need to change your entity method to
/* Message has many Replies */
public function replies() {
return \Cache::remember('messages_' . $this->id . '_replies', $this->expiration, function () {
return $this->hasMany('App\Model\Entities\ReplyEntity', 'fk_message_id', 'id')->orderBy('position', 'asc')->get();
});
}
and in the controller just get it with
$replies = $message->replies();
Or use an alternative method for collection sortBy( https://laravel.com/docs/7.x/collections#method-sortby )

Laravel how to create empty relationship?

I have a condition inside a relationship where if the user is logged in it will return the relation and if not i want it to return empty relationship.
here is what i want :
public function dummy()
{
return (auth()->user()) ? $this->hasOne(blah::class) : emptyrelationship();
}
You should check with DD() what is being returned as you like.
If there's no data for the relationship to show, it will just return no data.
To return an empty relationship instead of null, you can try this:
public function item()
{
return $this->belongsTo(Item::class)
->withDefault(function () {
return new Item();
});
}
Try This example
public function shop(){
if(true) {
return $this->newQuery(); // or newQueryWithoutScopes()
}
return $this->belongsTo('App\Models\Shop');
}
If there is no user in the user table collection will return relationship as "relationship: user: []" as blank only if you do dd($var) on your query,then you can check though conditions in your code;
Eloquent has a method for that newModelInstance
Best to keep the eloquent model standard relationship and move logic elsewhere
public function dummy()
{
return $this->hasOne(blah::class);
}
$dummy = $model->dummy;
if (!$dummy) {
$dummy = $model->dummy()->newModelInstance();
}

Laravel 4:: Returning models and its relationship

I would like to return the model and part of its relationship
EX::
User model
public function comments()
{
return $this->hasMany('comments');
}
Comments model
public function user()
{
return $this->belongsTo('user');
}
Can I return all comments and the user's name associated with the comment?
The desired effect is
$comment = Comments::find($id);
$comment->user;
return $comment;
This will return the one comment and the associated user full model. I just need the name of the user. And this does not works if I call Comments::all()
Thank you in advance.
You're looking for Eloquent's Eager Loading
Assuming your Comments model has a method user():
public function user()
{
return $this->belongsTo('User');
}
You should be able to do this in your controller:
$comments = Comments::with('user')->where('post_id', $post_id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $comments;
You can do the opposite as well:
Assuming your User model has a method 'comments()', like so:
public function comments()
{
return $this->hasMany('Comment');
}
Inside of your controller, you should be able to do the following, assuming your have the $id of the user available:
$user = User::with('comments')->find($id);
// Return JSON, as is Laravel's convention when returning
// Eloquent model directly
return $user;

Categories