I have a database which is set out with a news and a news categories tables.
I have news which has a category 1 which links to a foreign key of the categories table where the category value equals the id in the categories table.
I'm trying to make a controller that gets the category name rather than the category ID when returning the results as a JSON response.
So far I have this inside of a model:
public function category()
{
return $this->belongsTo(NewsCategories::class);
}
And then I'm doing this inside of a controller:
public function index()
{
$news = new News();
$news = $news->category()->get();
return response()->json(['data' => $news], 200);
}
But the JSON response that gets returned is empty. I have googled some things but haven't really found anything useful regarding getting the foreign field which is title within the categories table.
This is the response that I get
{
data: [ ]
}
The first issue is that you're under the impression that your new News
instance has linked categories:
$news = new News();
This will yield just an empty model instance; it has no database representation yet. Try fetching categories through a populated model instance:
$news = News::first();
// Or:
$news = News::find(1);
and retry the JSON response.
Second issue is that by calling $news->category()->get()
you're actually querying the relation. If you only need to access the title, try $news->category->title
which will load the associated category record and access the title
field for you.
Regarding your comment, read on eager/lazy loading.