One place for hosting & domains

      Records

      How To Insert New Database Records 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 practice the examples explained throughout the series, you’ll improve a demo application with new models and relationships.

      In a previous section of this series, you set up two models for a one-to-many relationship between the LinkList and Link models. In this section, you’ll learn how to insert links and lists in the database using Eloquent models. To limit the scope of this work, you’ll use custom Artisan commands to manage links and lists from the command line, which won’t require a web form.

      One of the biggest advantages of using an ORM system is the ability to manipulate rows in a database table as objects within your codebase. With Eloquent, as with other ORMs, the object itself provides methods that can be used to persist it to the database, saving you the work of writing SQL statements and manually managing data within tables.

      When working with one-to-many relationships in Laravel Eloquent, you have a few different options to save related models. In most cases, you’ll need to first set up the model representing the one side of the relationship, which in this demo is the LinkList model, and save that to the database. After doing that, you’ll be able to reference this model (which, once saved, represents a database record) when setting up the many side of the relationship (the Link model). That also means you’ll need to first have one or more lists in order to be able to create links.

      Before creating a new command to insert lists, however, you should update the existing link:new command to support the list feature.

      Open the following file in your code editor:

      app/Console/Commands/LinkNew.php
      

      You’ll see code like this:

      app/Console/Commands/LinkNew.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkNew extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:new";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Create a New Link';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $url = $this->ask('Link URL:');
      
              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      
              $description = $this->ask('Link Description:');
      
              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
      
              if ($this->confirm('Is this information correct?')) {
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $link->save();
      
                  $this->info("Saved.");
              }
      
              return 0;
          }
      }
      
      

      The handle() method is where the command executes its procedures. This is what it does:

      1. The ask() method, made available through the parent IlluminateConsoleCommand class, is a method used to obtain input from a user in the command line. This will prompt a user for a link, and validate the input to make sure it’s a valid URL.
      2. The script then asks for an optional description.
      3. Once values for url and description are obtained, the script will prompt for a confirmation using the confirm() method, available through the parent IlluminateConsoleCommand.
      4. When a confirmation is submitted with y or yes, the script will set up a new link object and save it to the database using the save() method, available through the model’s parent IlluminateDatabaseEloquentModel class.
      5. The script outputs a message to inform the user that the link was saved to the database, using the info output method.

      Note about return values: in the context of command line applications running on bash, non-zero return values are used to signal that the application exited in error, while 0 means it exited with success.

      If you run the link:new command now, it will break before it is finished because the database expects every link to be connected to a list. You’ll need to let the user choose which list a link should be included in, using a default list if none is provided by the user.

      The following code will ask the user to specify a list or leave it blank to use the default list. Then, it will try to locate the list or create a new list using the specified slug in case the list doesn’t exist yet. To retrieve a list provided by the user, this code uses the firstWhere method to find a list based on its slug field. Finally, it saves the new link using the links() relationship that can be accessed from the LinkList object.

      Substitute the current content in your LinkNew command class with:

      app/Console/Commands/LinkNew.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use AppModelsLinkList;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkNew extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:new";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Create a New Link';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $url = $this->ask('Link URL');
      
              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      
              $description = $this->ask('Link Description');
              $list_name = $this->ask('Link List (leave blank to use default)') ?? "default";
      
              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
              $this->info("Listed in: " . $list_name);
      
              if ($this->confirm('Is this information correct?')) {
                  $list = LinkList::firstWhere('slug', $list_name);
                  if (!$list) {
                      $list = new LinkList();
                      $list->title = $list_name;
                      $list->slug = $list_name;
                      $list->save();
                  }
      
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $list->links()->save($link);
      
                  $this->info("Saved.");
              }
      
              return 0;
          }
      }
      
      

      Save and close the file when you’re done. Then, run the command with:

      • docker-compose exec app php artisan link:new

      You’ll be prompted to provide a URL, a description, and a list name, in case you don’t want to save this link to the default list.

      Once you save your new link, if you run the link:show command, you should see the new link added to the results. However, there is no information included in the output about lists yet. You’ll need to update the LinkShow command to include a column that displays this information.

      Open the app/Console/Commands/LinkShow.php file in your code editor:

      app/Console/Commands/LinkShow.php
      

      This is how the class should look like now:

      app/Console/Commands/LinkShow.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      
      class LinkShow extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:show";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'List links saved in the database';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $headers = [ 'id', 'url', 'description' ];
              $links = Link::all(['id', 'url', 'description'])->toArray();
              $this->table($headers, $links);
      
              return 0;
          }
      }
      

      You’ll see that the current handle() method is fetching a certain number of fields and converting the result to an array. By default, results come from Eloquent as an Eloquent Collection, so this function converts them to an array in order to use that data within the table() method. The problem is that when the array conversion is made, you lose the relationship between class models (Link and LinkList), which makes it more difficult to access information about the list that a link is connected to.

      You’ll need to change this code so that it fetches the full Link object, including the related objects from the database. To create an array that is suitable for using with the table() method, you can iterate through the collection of results returned by Link::all().

      Replace the current contents in the app/Console/Commands/LinkShow.php file with the following code:

      app/Console/Commands/LinkShow.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      
      class LinkShow extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:show";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'List links saved in the database';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $headers = [ 'id', 'url', 'list', 'description' ];
              $links = Link::all();
      
              $table_rows = [];
              foreach ($links as $link) {
                  $table_rows[] = [ $link->id, $link->url, $link->link_list->slug, $link->description ];
              }
      
              $this->table($headers, $table_rows);
      
              return 0;
          }
      }
      
      

      Now, if you run the link:show method, you’ll see an additional column showing the list slug:

      Output

      +----+-----------------------------------------------------------------------------------------+-----------+--------------------------------------+ | id | url | list | description | +----+-----------------------------------------------------------------------------------------+-----------+--------------------------------------+ | 1 | https://digitalocean.com | default | DigitalOcean Website | | 2 | https://digitalocean.com/community/tutorials | tutorials | DO Tutorials | | 3 | https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04 | tutorials | Initial server setup on ubuntu 20.04 | +----+-----------------------------------------------------------------------------------------+-----------+--------------------------------------+

      Later in this tutorial series, you’ll update the front end and main route code to show links organized into lists. For now, you’ll use the command line to add, migrate, and validate your changes to the database and models.

      The next tutorial in this series will demonstrate another way of inserting new records in the database using Eloquent models, this time through the use of database seeders.

      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 Create Artisan Commands To Manage Database Records in Laravel



      Part of the Series:
      How To Build a Links Landing Page in PHP with Laravel and Docker Compose

      Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

      At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

      If you followed along with this series so far, your database tables should be all set. However, you still need to implement a way to let users insert new entries in the links table.

      To limit the scope of this series while also making the application fully-functional, you’ll set up Artisan commands to create and delete links in the database. Artisan is the command line tool that comes with Laravel, offering a number of utilities to speed up the development process, from generating boilerplate code to deleting and re-creating the application’s database.

      Using the command line interface to manage your application can be an alternative to web forms and secured areas, since it requires a user to be logged on the server in order to execute such commands instead of being authenticated from a browser. If you decide later on to create a secured area for your application, you can create web forms to allow a registered user to submit a new link to the database.

      Artisan commands are often used to perform application tasks that should run in the background, either manually or automatically via a scheduling mechanism such as Crontab. They can also be used to facilitate prototyping new application features that need to be configured dynamically, depending on input from an authorized user.

      To get started, create a new Artisan command using the make:command helper:

      • docker-compose exec app php artisan make:command LinkNew

      Output

      Console command created successfully.

      This will create a file named LinkNew.php, located at the app/Console/Commands directory. In this class, which extends from the IlluminateConsoleCommand parent class, you’ll need to implement a handle method that will be executed when this command is called. To define the signature of the command, you’ll set the $signature protected property to link:new.

      Open the new file using your text or code editor of choice. Here, we’ll use nano:

      • nano app/Console/Commands/LinkNew.php

      A few different things will need to happen in the handle method so that you are able to save a new link to the database. First, you’ll prompt for the user’s input in order to obtain the link URL.

       $url = $this->ask('Link URL:');
      

      Then, you’ll use the filter_var function to validate that the input obtained from the user is a valid URL. If the link is invalid, you’ll show an error and exit the application with status code 1, which means the application exited in error.

              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      

      If the link is valid, you’ll continue and ask for the link description using the same method as before.

       $description = $this->ask('Link Description:');
      

      You’ll then ask for a final confirmation that all data is correct, using the confirm helper. If the user confirms, the link is finally inserted in the database. You’ll use the Link Eloquent model created in a previous part of this series to interact with the database.

              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
      
              if ($this->confirm('Is this information correct?')) {
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $link->save();
      
                  $this->info("Saved.");
              }
      

      The application exits with a 0, representing a success status (0 errors).

      return 0;
      

      The following code contains the full implementation of these steps. Replace the current content in your LinkNew class with:

      app/Console/Commands/LinkNew.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkNew extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:new";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Create a New Link';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $url = $this->ask('Link URL:');
      
              if (!filter_var($url, FILTER_VALIDATE_URL)) {
                  $this->error("Invalid URL. Exiting...");
                  return 1;
              }
      
              $description = $this->ask('Link Description:');
      
              $this->info("New Link:");
              $this->info($url . ' - ' . $description);
      
              if ($this->confirm('Is this information correct?')) {
                  $link = new Link();
                  $link->url = $url;
                  $link->description = $description;
                  $link->save();
      
                  $this->info("Saved.");
              }
      
              return 0;
          }
      }
      

      Save and close the file when you’re done.

      To execute the command and insert a new link in the database, run:

      • docker-compose exec app php artisan link:new

      Output

      Link URL:: > https://digitalocean.com/community Link Description:: > DigitalOcean Community New Link: https://digitalocean.com/community - DigitalOcean Community Is this information correct? (yes/no) [no]: > yes Saved.

      Feel free to add a few more links if you want to.

      Next, you’ll need to create a new Artisan command to show the list of all links.You can call it link:list. Create the new command with:

      • docker-compose exec app php artisan make:command LinkList

      Open the command class using your text or code editor of choice:

      • nano app/Console/Commands/LinkList.php

      Within the handle method of this command, you’ll query for all rows in the links table. You can use the Link model to access the underlying database query methods that Eloquent provides. To exhibit the results nicely in the command line, you can use the table output helper:

              $headers = [ 'id', 'url', 'description' ];
              $links = Link::all(['id', 'url', 'description'])->toArray();
              $this->table($headers, $links);
      
              return 0;
      

      The following code contains the full implementation of the link:list command. Replace the content in your LinkList.php file with :

      app/Console/Commands/LinkList.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      
      class LinkList extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:list";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'List links saved in the database';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $headers = [ 'id', 'url', 'description' ];
              $links = Link::all(['id', 'url', 'description'])->toArray();
              $this->table($headers, $links);
      
              return 0;
          }
      }
      

      Save and close the file when you are done.

      To run this command and show a list of all links already inserted in the linkstable, run:

      • docker-compose exec app php artisan link:list

      Output

      +----+------------------------------------+--------------+ | id | url | description | +----+------------------------------------+--------------+ | 1 | https://digitalocean.com/community | DO Community | | 2 | https://laravel.com | Laravel | +----+------------------------------------+--------------+

      Finally, you’ll create a command to delete links:

      • docker-compose exec app php artisan make:command LinkDelete

      Output

      Console command created successfully.

      Open the new file using your text or code editor of choice:

      • nano app/Console/Commands/LinkDelete.php

      You can name this command link:delete. To know which link must be deleted, you’ll need to require that users provide an additional argument when calling the command: the ID of the link. This is also set within the $signature variable, which defines how your command is called and what arguments, mandatory or not, should be provided:

      protected $signature="link:delete {link_id}";
      

      The handle method for this command will implement a few different instructions. First, you’ll obtain the Link ID that should have been provided within the command call.

      $link_id = $this->argument('link_id');
      

      Then, you’ll obtain the referenced link from the database, using the Eloquent method find that is available through your Link model.

      $link = Link::find($link_id);
      

      When the find method doesn’t find a database record with that ID, it will return null. You’ll check if that is the current value contained in the $link variable, and return an error in that case. The program will exit in error (code 1).

              if ($link === null) {
                  $this->error("Invalid or non-existent link ID.");
                  return 1;
              }
      

      When $link is not null, the command continues execution. You then use the confirm helper to ask for a user confirmation.

      if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
          // deletes link
      }
      

      When the user confirms the action by typing yes and hitting ENTER, you’ll call the delete method from the Link Eloquent model to delete the specified link from the database.

                  $link->delete();
                  $this->info("Link deleted.");
      

      The following code contains the full implementation for the list:delete command. Replace the content in your LinkDelete.php file with the following:

      app/Console/Commands/LinkDelete.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use IlluminateConsoleCommand;
      use IlluminateSupportFacadesDB;
      
      class LinkDelete extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="link:delete {link_id}";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Deletes a link from the database.';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $link_id = $this->argument('link_id');
              $link = Link::find($link_id);
      
              if ($link === null) {
                  $this->error("Invalid or non-existent link ID.");
                  return 1;
              }
      
              if ($this->confirm('Are you sure you want to delete this link? ' . $link->url)) {
                  $link->delete();
                  $this->info("Link deleted.");
              }
      
              return 0;
          }
      }
      

      Save and close the file when you’re done.

      Now when you want to delete a link from your links table, you’ll first need to obtain the link’s ID with artisan link:list, as demonstrated earlier on. Once you know the ID of a link, you can run the artisan link:delete command with:

      • docker-compose exec app php artisan link:delete LINK_ID

      Output

      Are you sure you want to delete this link? https://laravel.com (yes/no) [no]: > yes Link deleted.

      You’re now able to insert, list, and delete links in the application’s database, using Artisan commands executed from a command-line interface. In the next part of this series, you’ll set up the front end of your application using Blade templates and the Bulma CSS framework.



      Source link

      Troubleshooting DNS Records


      Updated by Linode

      Written by Linode

      Having problems with your DNS records? This guide to help get your DNS settings back on track. Follow these tips to troubleshoot DNS issues.

      Before You Begin

      The Domains section of the Linode Cloud Manager is a comprehensive DNS management interface that allows you to add DNS records for all of your domain names. For an introduction to DNS Manager including setting up DNS records, see the DNS Manager guide.

      Note

      Linode’s DNS service employs Cloudflare to provide denial of service (DDoS) mitigation, load balancing, and increased geographic distribution for our name servers. These factors make our service reliable, fast, and a great choice for your DNS needs.

      Note

      To use the Linode DNS Manager to serve your domains, you must have an active Linode on your account. If you remove all active Linodes, your domains will no longer be served.

      Wait for Propagation

      DNS updates will take effect, or propagate, within the time period set by your zone file’s TTL. If you’ve just made a DNS change and aren’t seeing it reflected yet, the new information may not be available for up to 48 hours.

      While you can’t control DNS caching at every point on the Internet, you do have control over your web browser. Try holding down the Shift key or the Control key (depending on your browser) while you refresh the page to bypass your browser’s cache of the old DNS data. You can also try bringing up your site in an alternate browser or editing your hosts file to preview your website without DNS.

      Set the Time To Live or TTL

      In the context of DNS, Time to Live (TTL) tells internet servers how long to cache particular DNS entries. The default TTL for Linode domain zone files is 24 hours. This is fine for most situations because most people don’t update their IP addresses often.

      However, there are times when you’ll want the TTL to be as low as possible. For instance, when you make a DNS change, you’ll want that change to propagate quickly. Otherwise, some people will see the new site right away, and others (who had the old data cached) will still be visiting the website at your old server. Long caching times can be even more problematic when it comes to email, because some messages will be sent to the new server and some to the old one.

      The solution is to lower your TTL before making a DNS change. You’ll want to lower the TTL first, before making any other DNS changes. Here’s a general overview of what should happen during a smooth DNS update:

      Note

      TTL is always written out in seconds, so 24 hours = 86400 seconds.

      1. Check the TTL value for the DNS record you will be updating. Typically, this will be 24 or 48 hours.
      2. Update the relevant DNS records 48 to 96 hours in advance (for a 24-48 hour record), taking into account any intermediate DNS servers. Lower the TTL to five minutes (300 seconds, or the lowest allowed value). Do not make any other changes at this time.
      3. Wait out the original 48 to 96 hours.
      4. Visit your domain’s DNS records in the Linode Cloud Manager again to update your IP address and anything else needed.
      5. The DNS changes should propagate within 30 minutes.

      Find Current DNS Information

      Sometimes you may need to find the current DNS information for a domain. There are two great tools for doing this:

      • dig: Look up individual DNS entries. For example, you can find the IP address where your domain resolves.

      • whois: Find your registrar and nameserver information for your domain.

      If you’re using a computer that runs macOS or Linux, you can use these tools from the command line. To find your domain’s IP (the primary A record), run:

      dig example.com
      

      Look in the answer section of the output to locate your IP address. You can also query for other types of records. For example, to see the mail records for a domain, run:

      dig mx example.com
      

      This returns all of your domain’s MX records.

      To find your domain’s registrar and nameserver information, run:

      whois example.com
      

      This generates a large amount of information about the domain. The basic information you need will be near the top of the output, so you might have to scroll back to see it.

      For a web-based tool, you can also use kloth.net for dig requests and whois.net for WHOIS requests. Note that since you’re running these lookups from a third-party website, the information they find is not necessarily what your local computer has cached. There should be a difference only if you’ve made recent changes to your DNS information.

      For more information and examples on how to use dig, see our Use dig to Perform Manual DNS Queries guide.

      Name Resolution Failures

      If you have DNSSEC enabled at your domain’s registrar it will cause name resolution failures such as NXDOMAIN when an attempt is made to access the DNS. This is because the Linode DNS Manager does not support DNSSEC at this time.

      This guide is published under a CC BY-ND 4.0 license.



      Source link