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

Wednesday, January 5, 2022

[FIXED] Cakephp dynamic homepage without slug

 January 05, 2022     cakephp-3.0     No comments   

Issue

I am trying to build a dynamic page system with cakephp 3. Using slugs I can show pages and content. But on the homepage, it is just using the default view template.

I have the routes as followed:

$routes->connect('/', ['controller' => 'pages', 'action' => 'display', 'home']);
$routes->connect('/:slug', ['controller' => 'pages', 'action' => 'view'], ['pass' => ['slug'], 'slug' => '[^\?/]+']);

Which works for the none homepage pages.

But I want to use the homepage as / (e.g. localhost:8000/)

And not /home (e.g. localhost:8000/home).

Currently the view function in the pages controller looks like this:

public function view($slug = null) 
{
    $pages = TableRegistry::getTableLocator()->get('webpages');

    $page = $pages->findBySlug($slug)->firstOrFail();
    $this->set(compact('page'));
}

Any idea?


Solution

Seems I already found the solution.

I changed the routing to just the following line:

$routes->connect('/*', ['controller' => 'pages', 'action' => 'view']);

Then I changed the view as followed:

public function view($slug = null) 
{
    $pages = TableRegistry::getTableLocator()->get('webpages');
    if($slug == null){
        $query = $pages->find('all', [
            'conditions' => ['ishome' => 1]
        ]);
    } else {
        $query = $pages->find('all', [
            'conditions' => ['slug' => $slug]
        ]);
    }
    $page = $query->first();
    $this->set(compact('page'));
}

I use the answer from the following comment, but had to modify it a bit, since that code was used for an older version of cakephp (I am using cakekphp 3.8).

https://stackoverflow.com/a/3975923/6181243



Answered By - udarts
  • 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