One place for hosting & domains

      Data

      How To Populate a Database with Sample Data using Laravel Seeders and Eloquent Models



      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.

      Laravel’s Seeders are special classes that live in the database/seeders directory in a Laravel project that allow you to programmatically insert a collection of default or sample records in the database. The demo application has a seeder class that imports links from a links.yml file in the root of the application folder.

      In your code editor, open the following file:

      database/seeders/LinkSeeder.php
      

      It will contain the following code:

      database/seeders/LinkSeeder.php

      <?php
      
      namespace DatabaseSeeders;
      
      use AppModelsLink;
      use IlluminateDatabaseSeeder;
      use IlluminateSupportFacadesDB;
      use SymfonyComponentYamlYaml;
      
      class LinkSeeder extends Seeder
      {
          /**
           * Run the database seeds.
           *
           * @return void
           */
          public function run()
          {
              //only import seeds if DB is empty.
              if (!Link::count()) {
                  $this->importLinks();
              }
          }
      
          /**
           * Imports Links from the default links.yml file at the root of the app.
           * Change that file to import a set of personal basic links you want to show
           * as soon as the application is deployed.
           */
          public function importLinks()
          {
              $links_import_path = __DIR__ . '/../../links.yml';
      
              $yaml = new Yaml();
              if (is_file($links_import_path)) {
                  $links = $yaml->parsefile($links_import_path);
      
                  foreach ($links as $link) {
                      DB::table('links')->insert([
                          'url' => $link['url'],
                          'description' => $link['description']
                      ]);
                  }
              }
          }
      }
      
      

      Notice that this code does not use the Link model and instead uses the query builder to insert new links in the database. This is a different way of working with database records in Laravel that doesn’t depend on Eloquent models. Even though this works well, by using Eloquent models you’ll have access to a series of helpful methods and shortcuts to make your code more concise and easier to read.

      To improve this code, you’ll change the foreach loop to use Eloquent models instead of querying the database directly with the query builder. You’ll also have to create a default list of links (called $default_list in the following code) before the loop is started, so that you can reference this list in each new link created.

      Replace the current content in your seeder class with the following code:

      database/seeders/LinkSeeder.php

      <?php
      
      namespace DatabaseSeeders;
      
      use AppModelsLink;
      use AppModelsLinkList;
      use IlluminateDatabaseSeeder;
      use IlluminateSupportFacadesDB;
      use SymfonyComponentYamlYaml;
      
      class LinkSeeder extends Seeder
      {
          /**
           * Run the database seeds.
           *
           * @return void
           */
          public function run()
          {
              //only import seeds if DB is empty.
              if (!Link::count()) {
                  $this->importLinks();
              }
          }
      
          /**
           * Imports Links from the default links.yml file at the root of the app.
           * Change that file to import a set of personal basic links you want to show
           * as soon as the application is deployed.
           */
          public function importLinks()
          {
              $links_import_path = __DIR__ . '/../../links.yml';
      
              $yaml = new Yaml();
              if (is_file($links_import_path)) {
                  $links = $yaml->parsefile($links_import_path);
      
                  $default_list = new LinkList();
                  $default_list->title = "Default";
                  $default_list->description = "Default List";
                  $default_list->slug = "default";
                  $default_list->save();
      
                  foreach ($links as $link) {
                      $seed_link = new Link();
                      $seed_link->url = $link['url'];
                      $seed_link->description = $link['description'];
      
                      $default_list->links()->save($seed_link);
                  }
              }
          }
      }
      
      
      

      The updated code uses an object-oriented approach for setting up the properties for the LinkList and List models that are translated into table columns by Eloquent. The final line of the for loop uses the $default_list reference to the links table, which is accessed via the method links(), to save new links within that list.

      Save the file when you’re done. Laravel seeders will only run when the database is empty, so as to not conflict with actual data that was inserted in the database by other means. Thus in order to run the modified seeder, you’ll need to wipe the database once again with the artisan db:wipe command..

      Run the following command to wipe the development database:

      • docker-compose exec app php artisan db:wipe

      Output

      Dropped all tables successfully.

      Now to recreate the tables and run the updated seeders, you can use the following artisan migrate --seed command:

      • docker-compose exec app php artisan migrate --seed

      You should receive output that is similar to the following:

      Output

      Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (124.20ms) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (121.75ms) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (112.43ms) Migrating: 2020_11_18_165241_create_links_table Migrated: 2020_11_18_165241_create_links_table (61.04ms) Migrating: 2021_07_09_122027_create_link_lists_table Migrated: 2021_07_09_122027_create_link_lists_table (112.18ms) Seeding: DatabaseSeedersLinkSeeder Seeded: DatabaseSeedersLinkSeeder (84.57ms) Database seeding completed successfully.

      In the next chapter of this series, you’ll learn in more detail how to query database records with Eloquent.

      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

      What is Data Analysis?


      Data analysis is the practice of investigating the structure of data and using it to identify patterns and possible solutions to problems. A foundational element of data science, data analysis draws on methodologies from statistics, mathematics, and computer science to analyze data from past events and to predict possible outcomes.

      One important trend within data analysis is machine learning, which attempts to train algorithms based on preexisting data so that they may automatically classify or predict future data. In this way, machine learning enables practices such as automated decision-making.

      For more information about data analysis, check out our data analysis tag page, and An Introduction to Machine Learning.



      Source link

      Encrypting Your MongoDB Data



      Part of the Series:
      MongoDB Security: Best Practices to Keep Your Data Safe

      MongoDB, also known as Mongo, is a document database used in many modern web applications. As with any database management system, it’s critical that those responsible for managing a Mongo database adhere to the recommended security best practices, both to prevent data from being lost in the event of a disaster and to keep it out of the hands of malicious actors.

      This series of conceptual articles provides a high-level overview of MongoDB’s built-in security features while also highlighting some general database security best practices.

      Encryption is the process of converting a piece of information from plaintext, the information’s original form, into ciphertext, an unreadable form that can only be read by a person or computer that has the right cipher to decrypt it. If a malicious actor were to intercept a piece of encrypted data, they wouldn’t be able to read it until they’re able to decrypt it.

      You can encrypt communications between your MongoDB instance and whatever clients or applications need access to it by configuring it to require connections that use Transport Layer Security, also known as TLS. Like it’s predecessor, Secure Sockets Layer (SSL), TLS is a cryptographic protocol that uses certificate-based authentication to encrypt data as it’s transmitted over a network.

      Note that TLS only encrypts data as it moves over a network, otherwise known as data in-transit. Even if you’ve configured Mongo to require connections to be made with TLS, the static data stored on the database server, called data at rest, will still be unencrypted. It isn’t possible to encrypt data at rest with the free Community Edition of MongoDB, but it is possible with Mongo’s paid subscription-based Enterprise Edition.

      Even with both encryption-at-rest and encryption-in-transit enabled, though, your sensitive data could potentially still be accessed by an unapproved user. Consider, for example, a scenario where you’ve deployed a sharded NoSQL document database to store data for an ice cream delivery application you’ve developed. The database management system allows you to encrypt data at rest, which you enable, and you also configure it to require encrypted TLS connections between the shards as well as any clients.

      In this example situation, when a customer places an order they’re asked to submit a few pieces of sensitive information, like their home address or their credit card number. The application then writes this information to the database in a document, like this:

      {
        "name" : "Sammy Shark",
        "address" : {
          "street" : "602 Surf Ave",
          "city" : "Brooklyn",
          "state" : "New York",
          "zip" : 11224
        },
        "phone" : "555-555-1234",
        "creditcard" : "1234567890123456"
      }
      

      This is a potential security vulnerability, since anyone who has privileges to access the database could see and take advantage of your customers’ sensitive information.

      To help mitigate this type of risk, since version 4.2 the official MongoDB drivers allow you to perform client-side field level encryption. This means that, when properly configured, an application can encrypt certain fields within a document before the data is sent to the database. Once the data has been written to the database, only applications or clients that can present the correct encryption keys will be able to decrypt and read the data in these fields. Otherwise, the data document would look similar to this, assuming the street, city, zip, phone, and creditcard fields have been encrypted on the client’s side:

      {
        "name" : "Sammy Shark",
        "address" : {
          "street" : BinData(6,"eirefi3eid5feiZae9t+oot0noh9oovoch3=iethoh9t"),
          "city" : BinData(6,"xiesoh+aiveez=ngee1yei+u0aijah2eeKu7jeeB=oGh"),
          "state" : "New York"
          "zip" : BinData(6,"CoYeve+ziemaehai=io1Iliehoh6rei2+oo5eic0aeCh")
        },
        "phone" : BinData6,"quas+eG4chuolau6ahq=i8ahqui0otaek7phe+Miexoo"),
        "creditcard" : BinData6,"rau0Teez=iju4As9Eeyiu+h4coht=ukae8ahFah4aRo="),
      }
      

      MongoDB stores encrypted values as binary data, as indicated by the BinData class labels in the previous example. The 6 in each value represents the binary subtype in which the data is stored, and indicates the kind of binary data that’s been encoded. Values that have been encrypted with Mongo’s client-side field level encryption always use subtype 6.



      Source link