One place for hosting & domains

      Limit

      How To Limit and Paginate Query Results in Laravel Eloquent



      Part of the Series:
      A Practical Introduction to Laravel Eloquent ORM

      Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. In this project-based series, you’ll learn how to make database queries and how to work with relationships in Laravel Eloquent. To follow along with the examples demonstrated throughout the series, you’ll improve a demo application with new models and relationships. Visit the series introduction page for detailed instructions on how to download and set up the project.

      Throughout this series, you have been adding new links to your demo application to test out several features from Laravel Eloquent. You may have noticed that the main index page is getting longer each time you add a new link, since there is no limit to the number of links shown in the application. Although that won’t be an issue when you have a small number of database entries, in the long term that might result in longer loading times for your page, and a layout that is more difficult to read due to the amount of content spread in a single page.

      In this part of the series, you’ll learn how to limit the number of results in a Laravel Eloquent query with the limit() method, and how to paginate results with the simplePaginate() method.

      Limiting Query Results

      To get started, you’ll update your main application route (/) to limit the number of links that are listed on your index page.

      Start by opening your web routes file in your code editor:

      routes/web.php
      

      Then, locate the main route definition:

      routes/web.php

      Route::get('/', function () {
          $links = Link::all()->sortDesc();
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      });
      

      The highlighted line shows the query that obtains all links currently in the database, through the Link model all() method. As explained in a previous part of this series, this method is inherited from the parent Model class, and returns a collection with all database records associated with that model. The sortDesc() method is used to sort the resulting collection in descending order.

      You’ll now change the highlighted line to use the database query sorting method orderBy(), which orders query results at the database level, instead of simply reordering the full set of rows that is returned as an Eloquent Collection via the all() method. You’ll also include a chained call to the limit() method in order to limit the query results. Finally, you’ll use the get() method to obtain the filtered resultset as an Eloquent Collection.

      Replace your main route with the following code. The change is highlighted for your convenience:

      routes/web.php

      Route::get('/', function () {
          $links = Link::orderBy('created_at', 'desc')->limit(4)->get();
      
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      });
      

      The updated code will now pull the latest 4 links added to the database, no matter at which list. Because all links are added to lists, visitors can still go to specific lists to see the full list of links.

      Next, you’ll learn how to paginate results to make sure all links are still accessible, even though they don’t load all at once on a single page.

      Paginating Query Results

      Your index page now limits the number of links that are listed, so that your page isn’t overloaded with content, and gets rendered in a shorter amount of time. While this solution works well in many cases, you’ll need to make sure visitors can still access older links that aren’t visible by default. The most effective way to do so is by implementing a pagination where users can navigate between multiple pages of results.

      Laravel Eloquent has native methods to facilitate implementing pagination on database query results. The paginate() and simplePaginate() methods take care of generating pagination links, handling HTTP parameters to identify which page is currently being requested, and querying the database with the correct limit and offset in order to obtain the expected set of results, depending on the number of records per page you want to list.

      You’ll now update the Eloquent queries in routes/web.php to use the simplePaginate() method, which generates a basic navigation with previous and next links. Unlike the paginate() method, simplePaginate() doesn’t show information about the total number of pages in a query result.

      Open the routes/web.php file in your code editor. Start by updating the / route, replacing the limit(4)->get() method call with the simplePaginate() method:

      routes/web.php

      ...
      Route::get('/', function () {
          $links = Link::orderBy('created_at', 'desc')->simplePaginate(4);
      
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      });
      ...
      

      Next, locate the /{slug} route definition in the same file, and replace the get() method with the simplePaginate() method. This is how the code should look once you’re done:

      routes/web.php

      ...
      Route::get('/{slug}', function ($slug) {
          $list = LinkList::where('slug', $slug)->first();
          if (!$list) {
              abort(404);
          }
      
          return view('index', [
              'list' => $list,
              'links' => $list->links()->orderBy('created_at', 'desc')->simplePaginate(4),
              'lists' => LinkList::all()
          ]);
      })->name('link-list');
      ...
      

      This is how the finished routes/web.php file will look once you’re finished. The changes are highlighted for your convenience:

      routes/web.php

      <?php
      
      use IlluminateSupportFacadesRoute;
      use AppModelsLink;
      use AppModelsLinkList;
      
      /*
      |--------------------------------------------------------------------------
      | Web Routes
      |--------------------------------------------------------------------------
      |
      | Here is where you can register web routes for your application. These
      | routes are loaded by the RouteServiceProvider within a group which
      | contains the "web" middleware group. Now create something great!
      |
      */
      
      Route::get('/', function () {
          $links = Link::orderBy('created_at', 'desc')->simplePaginate(4);
      
          return view('index', [
              'links' => $links,
              'lists' => LinkList::all()
          ]);
      });
      
      Route::get('/{slug}', function ($slug) {
          $list = LinkList::where('slug', $slug)->first();
          if (!$list) {
              abort(404);
          }
      
          return view('index', [
              'list' => $list,
              'links' => $list->links()->orderBy('created_at', 'desc')->simplePaginate(4),
              'lists' => LinkList::all()
          ]);
      })->name('link-list');
      
      

      Save the file when you’re done.

      The database queries are now updated, but you still need to update your front end view to include code that will render the navigation bar. The resulting Eloquent collection obtained with simplePaginate() contains a method called links(), which can be called from the front end view to output the necessary HTML code that will render a navigation section based on a paginated Eloquent query.

      You can also use the links() method in a paginated Eloquent collection to access the inherent paginator object, which provides several helpful methods to obtain information about the content such as the current page and whether there are multiple pages of content or not.

      Open the resources/views/index.blade.php application view in your code editor:

      resources/views/index.blade.php
      

      Locate the end of the section tagged with the links class, which contains a foreach loop where links are rendered. Place the following piece of code after that section and before the final </div> tag on that page:

      resources/views/index.blade.php

              @if ($links->links()->paginator->hasPages())
                  <div class="mt-4 p-4 box has-text-centered">
                      {{ $links->links() }}
                  </div>
              @endif
      

      This code checks for the existence of multiple pages of results by accessing the paginator object and calling the hasPages() method. When that method returns true, the page renders a new div element and calls the links() method to print the navigation links for the related Eloquent query.

      This is how the updated index.blade.php page will look like once you’re finished:

      resources/views/index.blade.php

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>My Awesome Links</title>
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
      
          <style>
              html {
                  background: url("https://i.imgur.com/BWIdYTM.jpeg") no-repeat center center fixed;
                  -webkit-background-size: cover;
                  -moz-background-size: cover;
                  -o-background-size: cover;
                  background-size: cover;
              }
      
              div.link h3 {
                  font-size: large;
              }
      
              div.link p {
                  font-size: small;
                  color: #718096;
              }
          </style>
      </head>
      <body>
      <section class="section">
          <div class="container">
              <h1 class="title">
                  @if (isset($list))
                      {{ $list->title }}
                  @else
                      Check out my awesome links
                  @endif
              </h1>
              <p class="subtitle">
                  @foreach ($lists as $list)<a href="{{ route('link-list', $list->slug) }}" title="{{ $list->title }}" class="tag is-info is-light">{{ $list->title }} ({{ $list->links()->count() }})</a> @endforeach
              </p>
      
              <section class="links">
                  @foreach ($links as $link)
                      <div class="box link">
                          <h3><a href="{{ $link->url }}" target="_blank" title="Visit Link: {{ $link->url }}">{{ $link->description }}</a></h3>
                          <p>{{$link->url}}</p>
                          <p class="mt-2"><a href="{{ route('link-list', $link->link_list->slug) }}" title="{{ $link->link_list->title }}" class="tag is-info">{{ $link->link_list->title }}</a></p>
                      </div>
                  @endforeach
              </section>
      
              @if ($links->links()->paginator->hasPages())
                  <div class="mt-4 p-4 box has-text-centered">
                      {{ $links->links() }}
                  </div>
              @endif
          </div>
      </section>
      </body>
      </html>
      

      Save the file when you’re done updating it. If you go back to your browser window and reload the application page now, you’ll notice a new navigation bar whenever you have more than 4 links in the general listing or in any individual link list page.

      Updated application Landing Laravel with content pagination

      With a functional pagination in place, you can grow your content while making sure that older items are still accessible to users and search engines. In cases where you need only a fixed amount of results based on a certain criteria, where pagination is not necessary, you can use the limit() method to simplify your query and guarantee a limited result set.

      This tutorial is part of an ongoing weekly series about Laravel Eloquent. You can subscribe to the Laravel tag if you want to be notified when new tutorials are published.



      Source link

      How To Fix the WordPress Memory Exhausted Error by Increasing Your Site’s PHP Memory Limit


      As you may know, WordPress is built using PHP. This programming language is incredibly flexible, but it also has a few drawbacks. For example, if you don’t allocate enough memory for your WordPress installation, you might start running into the occasional “PHP Memory Exhausted” error.

      In a nutshell, this error means your server isn’t allocating enough resources for WordPress to execute the PHP scripts it needs to function properly. This issue can negatively affect your site’s functionality, but there are several ways you can fix and even prevent it.

      In this article, we’ll show you how to fix the memory exhausted problem by increasing your PHP memory limit. However, first, let’s talk about how to recognize this error and what it means!

      Why You’re Seeing a WordPress Memory Limit Error on Your Site

      As we mentioned earlier, the PHP memory limit error means you’re not allocating enough resources for your WordPress installation to function correctly. The problem usually presents itself with a message such as:

      The memory exhausted PHP fatal error.

      Don’t be scared by the word “fatal,” though. Your website isn’t broken, but you will need to make some changes to your WordPress installation if you want it to work properly. Specifically, you’ll want to increase your PHP memory limit.

      By “PHP memory limit,” we mean the amount of server memory that’s allocated to run PHP scripts. By default, that number should be around 64 MB or higher. In most cases, 64 MB is more than enough, however.

      Most hosting servers provide you with far more memory than that, so increasing the PHP allowed memory size shouldn’t negatively impact your website’s performance whatsoever. In fact, unless you’re using a cheap web host or you set up WordPress manually, your PHP memory limit shouldn’t be an issue at all.

      You can easily check to see what your PHP memory limit is by accessing your WordPress dashboard and navigating to Tools > Site Health > Info. Next, you can click on the Server tab and look for the PHP memory limit entry.

      A website with a high PHP memory size.

      Within the Server tab, you can also check other information such as your PHP version and the PHP time limit. The latter variable, which is in seconds, defines how long PHP scripts have to execute before they time out.

      For now, let’s focus on the PHP memory limit. As you can see, the above example has quite a high limit, which means that the website is unlikely to run into a WordPress Memory Exhausted error.

      If your site has a low memory limit (<64 MB), it’s in your best interests to increase it. There are a couple of ways you can do so.

      Take Your WordPress Website to the Next Level

      Whether you need help navigating your web hosting control panel, fixing an error, or finding the right plugin, we can help! Subscribe to our monthly digest so you never miss an article.

      How to Resolve the WordPress Memory Limit Error (2 Methods)

      As far as WordPress errors go, this one has a clear-cut cause and solution. You’re not allocating enough memory for your PHP installation, so you need to increase that number. In this section, we’ll go over two methods you can use: one manual technique and one that requires your wallet.

      1. Increase the PHP Memory Allocated to Your Website Manually

      WordPress enables you to declare your allowed memory size manually by modifying one of two files: .htaccess and wp-config.php. However, changing your WordPress installation’s .htaccess file can lead to site-wide errors since that file governs how it interacts with your server.

      Increasing your PHP memory limit through wp-config.php is, in most cases, the safest option, and it’s remarkably easy to do. All you need is a Secure File Transfer Protocol (SFTP) client such as FileZilla that you can use to connect to your website.

      Once you access your website via SFTP, open the WordPress root folder and look for the wp-config.php file within it.

      A WordPress wp-config.php file.

      Open that file using a text editor, and you should see something like this:

      Editing a wp-config.php file.

      To increase your PHP memory limit, you can simply add a single line of code anywhere after the <?php tag and before the part of the file that reads “/* That’s all, stop editing! Happy blogging. */”.

      This is the line of code to add:

      define( 'WP_MEMORY_LIMIT', 'XXXM' );

      You’ll need to replace the “XXX” variable within that line with the amount of memory you want to allocate to PHP. As we mentioned before, the absolute minimum you should settle for is 64 MB.

      However, you can also double the number to play it safe or increase it even further. For example, if you set a PHP memory limit of 256 MB, it would look like this:

      define( 'WP_MEMORY_LIMIT', ‘256M’);

      Once you’re set on a number, save the changes to wp-config.php and close the editor. Now return to your WordPress dashboard and navigate to Tools > Site Health > Info > Server to see if the changes went through.

      In some cases, declaring your PHP memory limit manually won’t work because you don’t have the necessary permissions to change that value. If you can’t adjust your WordPress memory size manually, that leaves you with one other option.

      2. Upgrade Your Website’s Hosting Plan

      Typically, if you use a decent WordPress hosting provider, you won’t need to worry about increasing your PHP memory limit. One caveat is that if you’re using shared hosting, you’ll likely face limited resources. So if you’re encountering this error, it might be time to upgrade to a better hosting plan.

      Upgrading your hosting package will usually result in an increase in available PHP memory. That means you’re much less likely to run into a WordPress memory limit error. The only limiting factor is your budget.

      If you can’t upgrade hosting plans right now, it might be worth contacting your provider’s support team and seeing if they can increase your PHP memory limit on their end. If they can’t, it might be time to switch to a better WordPress host that offers high PHP memory limits on affordable plans.

      Skip the Stress

      Avoid troubleshooting when you sign up for DreamPress. Our friendly WordPress experts are available 24/7 to help solve website problems — big or small.

      Want More WordPress Error Tips?

      Once you increase PHP memory on your WordPress website, we can help tackle other issues. We’ve put together several tutorials to help you troubleshoot every error message:

      Want more information on WordPress site management? Check out our WordPress Tutorials, a collection of guides designed to help you navigate the WordPress dashboard like an expert.

      Increasing PHP Memory Limit

      Running into a PHP fatal error can be worrying, but it’s not necessarily a cause for concern. Learning how to increase your PHP memory limit is relatively simple if you don’t mind using an SFTP client and adding a single line of code to one of WordPress’ core files.

      The alternative is to upgrade your hosting plan or opt for a better provider. Most WordPress-friendly hosting options offer high limits by default, so you’ll never run into a PHP memory exhausted error ever again.

      If you’re ready to use a web host optimized for WordPress websites, check out our DreamPress hosting packages! We offer optimized WordPress setups, so you spend less time troubleshooting errors and more time working on your website.



      Source link