PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How to get all records(related and non related) of Laravel belongsTo relationship?

 July 26, 2022     belongs-to, eloquent, laravel, relationship     No comments   

Issue

How can I get all the records from the relationship? I mean not only the related records, but also the rest.

Let's say I have a post which belongs to some category. If I want to change the category of this post I need a list of all available categories. Can I get this list from the relationship?

The Post model:

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

The Category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

In the PostsController I tried:

$postModel->category->find('all'); // Returns null
$postModel->category->all(); // Returns only the related categories

I know I can simply use the Category model in the PostsController, but I prefer to do it using the relationship.


Solution

If you feel you must use the relationship to get to the other model you could try:

$categories = $post->category()->getRelated()->get();


Answered By - lagbox
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing