I’m using Laravel 10 and I have made a table named pages
which stores the all static pages field data of website.
Here is the table:
Now in order to retrieve this data, at the Controller I added this:
use AppRepositoriesPageRepository;
use AppModelsPage;
class MainPagesController extends Controller
{
protected $pageRepository;
public function __construct(PageRepository $pageRepository)
{
$this->pageRepository = $pageRepository;
}
public function home()
{
$homeInfo = $this->pageRepository->getPageByType('home');
return view('admin.pages.main.home', compact('homeInfo'));
}
}
So I made a respository named PageRepository.php
which goes like this:
namespace AppRepositories;
use AppModelsPage;
class PageRepository
{
public function getPageByType(string $pageType)
{
return Page::where('pag_type', $pageType)->first();
}
public function getPageByName(string $pageName)
{
return Page::where('pag_name', $pageName)->first();
}
}
So it looks nice and perfect but at the Blade, when I do this:
@dd($homeInfo->where('pag_name', 'hero_image')->first()->pag_value)
I get this error:
Attempt to read property "pag_value" on null
However, the pag_name
with hero_image
has already a value named layer.png
and this error occurs for other pag_name
s as well!
So what’s going wrong here? How can I solve this issue?
2
Answers
When you called this on your controller
It will only get one record from your database since you already called the method
->first()
from your repository.So in your
$homeInfo
you can do this$homeInfo->pag_value
.Anyway to solve your problem, in your repository you can return the query object (don’t call the
first
method yet).Then your code in your blade file will work properly.
As per your code
$homeInfo
is not a collection, it’s a singlePage
instance (->first()
). So, you cannot chainwhere
method on it.use
and in your Blade file, you can use the
where
because$homeInfo
will be a collection