title: Laravel: How to create dynamic functions (methods) (using foreach loop) in class
body: <p>I'm building some small cms in laravel and now I need dynamic named methods and variables in my controller based on created page in my cms. I create few pages: <code>news, world, sport, business</code>. and now I need methods and variables in that methods named as pages names, dynamic.</p>
  
  <p>This is my AjaxController. </p>
  
  <pre><code>&lt;?php
  
  namespace App\Http\Controllers;
  
  use Illuminate\Http\Request;
  
  use App\Http\Requests;
  use App\Post;
  use App\Tag;
  use App\Page;
  
  class AjaxController extends Controller
  {
      protected $posts;
      protected $tags;
      protected $pages;
      protected $methods;
  
  
  
      public function __construct(Post $posts, Page $pages, Tag $tags)
      {
          $this-&gt;posts = $posts;
          $this-&gt;tags = $tags;
          $this-&gt;pages = $pages;
  
          $this-&gt;methods = $this-&gt;pages-&gt;where('parent_id', null)-&gt;where('title', '!=', 'Home')-&gt;orderBy('lft', 'asc')-&gt;get()-&gt;all();
  
      }
  
      foreach($this-&gt;methods as $method) {
  
          public function {$method-&gt;name}()
          {
              ${$method-&gt;name} = $this-&gt;posts-&gt;with('user')-&gt;with('category')-&gt;with('subcategory')-&gt;where('category_id', $method-&gt;id)-&gt;orderBy('created_at', 'desc')-&gt;paginate(3, ['*'], '{$method-&gt;name}');
  
              return view('ajax.'.$method-&gt;name, compact('{$method-&gt;name}'))-&gt;render();
          }
  
      }
  }
  </code></pre>
  
  <p>This doesnt work for me.</p>
  
  <p>Results that I need to get should look like this</p>
  
  <pre><code>public function news()
      {
          $news = $this-&gt;posts-&gt;with('user')-&gt;with('category')-&gt;with('subcategory')-&gt;where('category_id', 8)-&gt;orderBy('created_at', 'desc')-&gt;paginate(3, ['*'], 'news');
  
          return view('ajax.news', compact('news'))-&gt;render();
      }
  
  public function world()
          {
              $world = $this-&gt;posts-&gt;with('user')-&gt;with('category')-&gt;with('subcategory')-&gt;where('category_id', 10)-&gt;orderBy('created_at', 'desc')-&gt;paginate(3, ['*'], 'world');
  
              return view('ajax.world', compact('world'))-&gt;render();
          }
  
  
  public function sport()
      {
          $sport = $this-&gt;posts-&gt;with('user')-&gt;with('category')-&gt;with('subcategory')-&gt;where('category_id', 12)-&gt;orderBy('created_at', 'desc')-&gt;paginate(3, ['*'], 'sport');
  
          return view('ajax.sport', compact('sport'))-&gt;render();
      }
  
  ...
  </code></pre>
  
  <p>Please, how to loop and get dynamic methods and variables in class and parse that dynamic variables in laravel compact and paginate method?</p>