2

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 App\Repositories\PageRepository;
use App\Models\Page;

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 App\Repositories;

use App\Models\Page;

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?

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Pouya
  • 114
  • 1
  • 8
  • 36

2 Answers2

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 App\Repositories;

use App\Models\Page;

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.

aceraven777
  • 4,358
  • 3
  • 31
  • 55
0

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)
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85