skip to Main Content

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:

enter image description here

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_names as well!

So what’s going wrong here? How can I solve this issue?

2

Answers


  1. When you called this on your controller

    $homeInfo = $this->pageRepository->getPageByType('home');
    

    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).

    namespace AppRepositories;
    
    use AppModelsPage;
    
    class PageRepository
    {
        public function getPageByType(string $pageType)
        {
            return Page::where('pag_type', $pageType);
        }
    
        public function getPageByName(string $pageName)
        {
            return Page::where('pag_name', $pageName);
        }
    }
    

    Then your code in your blade file will work properly.

    Login or Signup to reply.
  2. As per your code $homeInfo is not a collection, it’s a single Page instance (->first()). So, you cannot chain where method on it.

    use

    public function getPageByType(string $pageType)
    {
        return Page::where('pag_type', $pageType)->get();
    }
    

    and in your Blade file, you can use the where because $homeInfo will be a collection

    @dd($homeInfo->where('pag_name', 'hero_image')->first()->pag_value)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search