One place for hosting & domains

      Delete

      How To Delete 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 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.

      In Eloquent, you can delete database records conveniently with the delete method from the parent Model class. The link:delete command, already implemented within the base version of the demo application, deletes links based on a valid link id. The application is still missing a command to delete lists.

      In the last part of this series, you’ll create a new command to delete lists. For simplicity, any links associated with the list to be deleted will be reassigned to the default link list.

      From your terminal, run the following to bootstrap a new Artisan command:

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

      This will create a new ListDelete.php file located at app/Console/Commands. Open the file in your code editor of choice:

      app/Console/Commands/ListDelete.php
      

      You’ll update this code to handle deleting a link list provided its unique slug, which is a URL-friendly name used to identify each list.

      This is what your handle() method needs to do:

      • Obtain a slug provided by the user and check for the existence of a list with a matching slug in the database.
      • If a valid list cannot be found, show an error message and exit.
      • If a valid list is found, prompt the user to confirm.
      • Reassign to the default list any links associated with the list that will be deleted.
      • Delete the list from the database.

      If you’ve been following along with all parts of the series so far, you have implemented similar code before when creating the LinkUpdate command. The main difference now is that you won’t need to prompt the user for additional info, and before running the delete() method you’ll need to run a mass update to change associated links to a different list.

      Replace the boilerplate code in your ListDelete.php file with the following:

      app/Console/Commands/ListDelete.php

      <?php
      
      namespace AppConsoleCommands;
      
      use AppModelsLink;
      use AppModelsLinkList;
      use IlluminateConsoleCommand;
      
      class ListDelete extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
          protected $signature="list:delete {list_slug}";
      
          /**
           * The console command description.
           *
           * @var string
           */
          protected $description = 'Delete Lists';
      
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();
          }
      
          /**
           * Execute the console command.
           *
           * @return int
           */
          public function handle()
          {
              $list_slug = $this->argument('list_slug');
              $list = LinkList::firstWhere('slug', $list_slug);
      
              if ($list === null) {
                  $this->error("Invalid or non-existent List.");
                  return 1;
              }
      
              if ($this->confirm("Confirm deleting the list '$list->title'? Links will be reassigned to the default list.")) {
                  $default_list = LinkList::firstWhere('slug', 'default');
                  if (!$default_list) {
                      $default_list = new LinkList();
                      $default_list->title="default";
                      $default_list->slug = 'default';
                      $default_list->save();
                  }
      
                  $this->info("Reassigning links to default list...");
      
                  Link::where('link_list_id', $list->id)->update(['link_list_id' => $default_list->id]);
      
                  $list->delete();
                  $this->info("List Deleted.");
              }
      
              return 0;
          }
      }
      

      Save the file.

      In the previous code, the handle() method starts by trying to locate a link list based on the provided slug. If a valid list can’t be found, the application exits in error. When a valid list is found, the confirm() method is called to ask the user for confirmation.

      When confirmed, the application will locate the default list or create a new one if necessary, assigning it to the $default_list variable.

      Next, it will locate and update all links that are associated with the list that is about to be deleted. The chained call to update() will update the referenced list ID on all links that match the query, using the condition defined within the previous where() call. This line is highlighted for your reference.

      Finally, the list is deleted with the delete() method, also highlighted. This method is available to all Eloquent models through the parent Model class.

      To delete a list, first run link:show to obtain all links currently in the database:

      • docker-compose exec app php artisan link:show

      Output

      +----+-------------------------------------------------+--------------+----------------------------------+ | id | url | list | description | +----+-------------------------------------------------+--------------+----------------------------------+ | 1 | https://digitalocean.com/community | digitalocean | DO Community | | 2 | https://digitalocean.com/community/tags/laravel | digitalocean | Laravel Tutorias at DigitalOcean | | 3 | https://digitalocean.com/community/tags/php | digitalocean | PHP Tutorials at DigitalOcean | | 4 | https://twitter.com/digitalocean | social | Twitter | | 5 | https://dev.to/digitalocean | social | DEV.to | | 6 | https://laravel.com/docs/8.x/eloquent | default | Laravel Eloquent Docs | +----+-------------------------------------------------+--------------+----------------------------------+

      To delete the digitalocean list and revert those links back to the default list, run:

      • docker-compose exec app php artisan list:delete digitalocean

      Confirm the deletion by typing y and hitting ENTER.

      Output

      Confirm deleting the list 'digitalocean'? Links will be reassigned to the default list. (yes/no) [no]: > y Reassigning links to default list... List Deleted.

      If you run the link:show() command again, you’ll see the updated information:

      Output

      +----+-------------------------------------------------+---------+----------------------------------+ | id | url | list | description | +----+-------------------------------------------------+---------+----------------------------------+ | 1 | https://digitalocean.com/community | default | DO Community | | 2 | https://digitalocean.com/community/tags/laravel | default | Laravel Tutorias at DigitalOcean | | 3 | https://digitalocean.com/community/tags/php | default | PHP Tutorials at DigitalOcean | | 4 | https://twitter.com/erikaheidi | social | Twitter | | 5 | https://dev.to/erikaheidi | social | DEV.to | | 6 | https://laravel.com/docs/8.x/eloquent | default | Laravel Eloquent Docs | +----+-------------------------------------------------+---------+----------------------------------+

      The application now has a dedicated command to delete lists of links.





      Source link

      How To Delete Data in SQL


      Introduction

      In Structured Query Language, more commonly known as SQL, the DELETE statement is one of the most powerful operations available to users. As the name implies, DELETE operations irreversibly delete one or more rows of data from a database table. Being such a fundamental aspect of data management, it’s important for SQL users to understand how the DELETE statement works.

      This guide will go over how to use SQL’s DELETE syntax to delete data from one or more tables. It will also explain how SQL handles DELETE operations that conflict with foreign key constraints.

      Prerequisites

      In order to follow this guide, you will need a computer running some type of relational database management system (RDBMS) that uses SQL. The instructions and examples in this guide were validated using the following environment:

      Note: Please note that many RDBMSs use their own unique implementations of SQL. Although the commands outlined in this tutorial will work on most RDBMSs, the exact syntax or output may differ if you test them on a system other than MySQL.

      You’ll also need a database and table loaded with some sample data which you can use to practice deleting data. We encourage you to read the following Connecting to MySQL and Setting up a Sample Database section for details on how to create a database and two tables which this guide will use in examples throughout.

      Connecting To MySQL and Setting Up a Sample Database

      If your SQL database system runs on a remote server, SSH into your server from your local machine:

      Then open up the MySQL server prompt, replacing sammy with the name of your MySQL user account:

      Create a database named deleteDB:

      • CREATE DATABASE deleteDB;

      If the database was created successfully, you’ll receive output like this:

      Output

      Query OK, 1 row affected (0.01 sec)

      To select the deleteDB database, run the following USE statement:

      Output

      Database changed

      After selecting the deleteDB database, create a couple tables within it. As an example, imagine that you and some of your friends started a club in which members can share music equipment with one another. To help you keep track of club members and their equipment, you decide to create a couple of tables. The first table will have the following four columns:

      • memberID: each club member’s identification number, expressed with the int data type. To ensure that each member has a unique ID, this column will have the AUTO_INCREMENT attribute which will cause SQL to automatically add integers to this column, starting with 1 and incrementing up from there. This column will also serve as the table’s primary key
      • name: each member’s name, expressed using the varchar data type with a maximum of 30 characters
      • homeBorough: this column will store the borough in which each member lives, again expressed using the varchar data type but with a maximum of only 15 characters
      • email: the email address through which each member can be contacted, expressed using the varchar data type with a maximum of 30 characters

      Create a table named clubMembers that has these four columns:

      • CREATE TABLE clubMembers (
      • memberID int AUTO_INCREMENT PRIMARY KEY,
      • name varchar(30),
      • homeBorough varchar(15),
      • email varchar(30)
      • );

      The next table will have the following columns:

      • equipmentID: a unique identifier for each piece of equipment. Values in this column will be of the int data type. Like the memberID column in the clubMembers table, this column will have the AUTO_INCREMENT attribute and will serve as the table’s primary key
      • equipmentType: what type of instrument or tool each row represents (e.g., guitar, mixer, amplifier, etc.). These values will be expressed using the varchar data type with a maximum of 30 characters
      • brand: the brand that produced each piece of equipment, again expressed using the varchar data type with a maximum of 30 characters
      • ownerID: this column will hold the ID number of the club member who owns the piece of equipment, expressed as an integer.

      In order to ensure that the ownerID column only holds values that represent valid member ID numbers, you could create a foreign key constraint that references the clubMember table’s memberID column. A foreign key constraint is a way to express a relationship between two tables. A foreign key does this by requiring that values in the column on which it applies must already exist in the column that it references. In the following example, the foreign key constraint requires that any value added to the ownerID column must already exist in the memberID column.

      Create a table with these columns and this constraint named clubEquipment:

      • CREATE TABLE clubEquipment (
      • equipmentID int AUTO_INCREMENT PRIMARY KEY,
      • equipmentType varchar(30),
      • brand varchar(15),
      • ownerID int,
      • CONSTRAINT fk_ownerID
      • FOREIGN KEY (ownerID) REFERENCES clubMembers(memberID)
      • );

      Note that this example provides a name for the foreign key constraint, fk_ownerID. MySQL will automatically generate a name for any constraint you add, but defining one here will be useful when we need to reference this constraint later on.

      Next, run the following INSERT INTO statement to load the clubMembers table with six rows of sample data:

      • INSERT INTO clubMembers (name, homeBorough, email)
      • VALUES
      • ('Rosetta', 'Manhattan', 'hightower@example.com'),
      • ('Linda', 'Staten Island', 'lyndell@example.com'),
      • ('Labi', 'Brooklyn', 'siffre@example.com'),
      • ('Bettye', 'Queens', 'lavette@example.com'),
      • ('Phoebe', 'Bronx', 'snow@example.com'),
      • ('Mariya', 'Brooklyn', 'takeuchi@example.com');

      Then run another INSERT INTO statement to load the clubEquipment table with twenty rows of sample data:

      • INSERT INTO clubEquipment (equipmentType, brand, ownerID)
      • VALUES
      • ('electric guitar', 'Gilled', 6),
      • ('trumpet', 'Yemehe', 5),
      • ('drum kit', 'Purl', 3),
      • ('mixer', 'Bearinger', 3),
      • ('microphone', 'Sure', 1),
      • ('bass guitar', 'Fandar', 4),
      • ('acoustic guitar', 'Marten', 6),
      • ('synthesizer', 'Korgi', 4),
      • ('guitar amplifier', 'Vax', 4),
      • ('keytar', 'Poland', 3),
      • ('acoustic/electric bass', 'Pepiphone', 2),
      • ('trombone', 'Cann', 2),
      • ('mandolin', 'Rouge', 1),
      • ('electric guitar', 'Vax', 6),
      • ('accordion', 'Nonher', 5),
      • ('electric organ', 'Spammond', 1),
      • ('bass guitar', 'Peabey', 1),
      • ('guitar amplifier', 'Fandar', 3),
      • ('cello', 'Yemehe', 2),
      • ('PA system', 'Mockville', 5);

      With that, you’re ready to follow the rest of the guide and begin learning about how to delete data with SQL.

      Deleting Data from a Single Table

      The general syntax for deleting data in SQL looks like this:

      • DELETE FROM table_name
      • WHERE conditions_apply;

      Warning: The important part of this syntax is the WHERE clause, as this is what allows you to specify exactly what rows of data should get deleted. Without it, a command like DELETE FROM table_name; would execute correctly, but it would delete every row of data from the table.

      Be aware that a successful DELETE operation is irreversible. If you were to run one without knowing exactly what data it will delete, there’s a chance that you could accidentally delete the wrong records. One way to help make sure you don’t accidentally delete the wrong data is to first issue a SELECT query to see what data will get returned by a DELETE operation’s WHERE clause.

      To illustrate, let’s say you wanted to remove any records related to music equipment made by the brand Korgi. To be safe, though, you decide to first write a query to see exactly what equipment records list Korgi in their brand column.

      To find what instruments in your table are made by Korg, you could run the following query. Note that unlike a SELECT query or an INSERT INTO operation, DELETE operations do not allow you to specify individual columns, as they’re intended to delete entire rows of data. To imitate this behavior, this query follows the SELECT keyword with an asterisk (*) which is SQL shorthand and represents “every column”:

      • SELECT * FROM clubEquipment
      • WHERE brand = 'Korgi';

      This query returns every column from the clubEquipment table, but only returns rows whose brand column contains the value Korgi:

      Output

      +-------------+---------------+-------+---------+ | equipmentID | equipmentType | brand | ownerID | +-------------+---------------+-------+---------+ | 8 | synthesizer | Korgi | 4 | +-------------+---------------+-------+---------+ 1 row in set (0.00 sec)

      To delete this row you would run a DELETE operation that has FROM and WHERE clauses identical to the previous SELECT statement:

      • DELETE FROM clubEquipment
      • WHERE brand = 'Korgi';

      Output

      Query OK, 1 row affected (0.01 sec)

      This output indicates that the DELETE operation only affected a single row. However, you can delete multiple rows of data with any WHERE clause that returns more than one row.

      The following SELECT query returns every record in the clubEquipment table whose equipmentType column contains the word electric:

      • SELECT * FROM clubEquipment
      • WHERE equipmentType LIKE '%electric%';

      Output

      +-------------+------------------------+-----------+---------+ | equipmentID | equipmentType | brand | ownerID | +-------------+------------------------+-----------+---------+ | 1 | electric guitar | Gilled | 6 | | 11 | acoustic/electric bass | Pepiphone | 2 | | 14 | electric guitar | Vax | 6 | | 16 | electric organ | Spammond | 1 | +-------------+------------------------+-----------+---------+ 4 rows in set (0.00 sec)

      Again, to delete these four records, rewrite this query operation but replace SELECT * with DELETE:

      • DELETE FROM clubEquipment
      • WHERE equipmentType LIKE '%electric%';

      Output

      Query OK, 4 rows affected (0.00 sec)

      You can also use subqueries to return and delete more granular result sets. A subquery is a complete query operation — meaning, an SQL statement that starts with SELECT and includes a FROM clause — embedded within another operation, following the surrounding operation’s own FROM clause.

      Say, for example, that you wanted to delete any equipment listed in the clubEquipment table owned by any member whose name begins with the letter “L.” You could first query for this data with a statement like this:

      • SELECT *
      • FROM clubEquipment
      • WHERE ownerID IN
      • (SELECT memberID FROM clubMembers
      • WHERE name LIKE 'L%');

      This operation returns every row from the clubEquipment table whose ownerID column appears in the values returned by the subquery beginning on the fourth line. This subquery returns the memberIDof any record whosename` value begins with “L”:

      Output

      +-------------+------------------+-----------+---------+ | equipmentID | equipmentType | brand | ownerID | +-------------+------------------+-----------+---------+ | 12 | trombone | Cann | 2 | | 19 | cello | Yemehe | 2 | | 3 | drum kit | Purl | 3 | | 4 | mixer | Bearinger | 3 | | 10 | keytar | Poland | 3 | | 18 | guitar amplifier | Fandar | 3 | +-------------+------------------+-----------+---------+ 6 rows in set (0.00 sec)

      You could then remove this data with the following DELETE statement:

      • DELETE FROM clubEquipment
      • WHERE ownerID IN
      • (SELECT memberID FROM clubMembers
      • WHERE name LIKE 'L%');

      Output

      Query OK, 6 rows affected (0.01 sec)

      Deleting Data from Multiple Tables

      You can delete data from more than one table in a single operation by including a JOIN clause.

      JOIN clauses are used to combine rows from two or more tables into a single query result. They do this by finding a related column between the tables and sorting the results appropriately in the output.

      The syntax for a DELETE operation that includes a JOIN clause looks like this:

      • DELETE table_1, table_2
      • FROM table_1 JOIN table_2
      • ON table_2.related_column = table_1.related_column
      • WHERE conditions_apply;

      Note that because JOIN clauses compare the contents of more than one table, this example syntax specifies which table to select each column from by preceding the name of the column with the name of the table and a period. This is known as a fully qualified column reference. You can specify which table a column should be selected from like this for any operation, although it’s not necessary when selecting only from a single table as we’ve done in the previous examples.

      To illustrate deleting data with a JOIN clause, say your club decides to limit what brands of musical equipment members can share. Run the following statement to create a table named prohibitedBrands in which you will list what brands are no longer acceptable for the club. This table only has two columns, both using the varchar data type, to hold each brand’s name and what country they operate in:

      • CREATE TABLE prohibitedBrands (
      • brandName varchar(30),
      • homeCountry varchar(30)
      • );

      Then load this new table with some sample data:

      • INSERT INTO prohibitedBrands
      • VALUES
      • ('Fandar', 'USA'),
      • ('Givson', 'USA'),
      • ('Muug', 'USA'),
      • ('Peabey', 'USA'),
      • ('Yemehe', 'Japan');

      Following that, the club decides to delete any records of equipment from the clubEquipment table whose brands appear in the prohibitedBrands table and are based in the United States.

      You could query for this data with an operation like the following SELECT statement. This operation joins the clubEquipment and prohibitedBrands tables together, only returning the rows whose brand and brandName columns share a common value. The WHERE clause refines this result set further by excluding any brand whose homeCountry column doesn’t include USA as its value:

      • SELECT *
      • FROM clubEquipment JOIN prohibitedBrands
      • ON clubEquipment.brand = prohibitedBrands.brandName
      • WHERE homeCountry = 'USA';

      Output

      +-------------+---------------+--------+---------+-----------+-------------+ | equipmentID | equipmentType | brand | ownerID | brandName | homeCountry | +-------------+---------------+--------+---------+-----------+-------------+ | 6 | bass guitar | Fandar | 4 | Fandar | USA | | 17 | bass guitar | Peabey | 1 | Peabey | USA | +-------------+---------------+--------+---------+-----------+-------------+ 2 rows in set (0.00 sec)

      That’s all the information we’re looking for; namely, each USA-based brand in the prohibitedBrands table that also appears in the clubEquipment table.

      To delete these brands from the prohbitedBrands table and the associated equipment from clubEquipment, rewrite the previous SELECT statement but replace SELECT * with DELETE followed by the names of both tables:

      • DELETE clubEquipment, prohibitedBrands
      • FROM clubEquipment JOIN prohibitedBrands
      • ON clubEquipment.brand = prohibitedBrands.brandName
      • WHERE homeCountry = 'USA';

      Output

      Query OK, 4 rows affected (0.01 sec)

      This output indicates that the operation deleted four rows of data: two rows from clubEquipment and two rows from prohibitedBrands. If you only wanted to delete the records from the clubEquipment table and maintain all the records in the prohibitedBrands table, you would only list clubEquipment after the DELETE keyword, and vice versa.

      Changing Foreign Key DELETE Behavior

      By default, any DELETE statement that would cause a conflict with a foreign key will fail.

      Recall from the Connecting to MySQL and Setting up a Sample Database section of the Prerequisites that the ownerID column of the clubEquipment table references the ownerID column of the clubEquipment table as a foreign key. This means that any value entered into the ownerID column must already exist in the memberID column.

      If you attempt to delete a row of data from the clubMembers table whose memberID value is used anywhere in the ownerID column, it will cause an error:

      • DELETE FROM clubMembers
      • WHERE memberID = 6;

      Output

      ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails

      You can avoid this error by first removing any rows in the child table (clubEquipment in this example) where the foreign key value exists in the parent table (clubMembers).

      Alternatively, you can change this behavior by replacing the existing foreign key constraint with one that treats DELETE operations differently.

      Note: Not every database management system or engine allows you to add or remove a constraint from an existing table as outlined in the following paragraphs. If you’re using an RDBMS other than MySQL, you should consult its official documentation to understand what limitations it has for managing constraints.

      To replace the current constraint, you must first remove it with an ALTER TABLE statement. Recall that in the CREATE TABLE statement for clubEquipment, we defined fk_ownerID as a name for the table’s foreign key constraint:

      • ALTER TABLE clubEquipment
      • DROP FOREIGN KEY fk_ownerID;

      Output

      Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0

      Following that, create a new foreign key constraint that’s configured to treat DELETE operations in a way that makes sense for the given use case. Aside from the default setting which prohibits DELETE statements that violate the foreign key, there are two other options available:

      • ON DELETE SET NULL: This option will allow you to delete records from the parent table, and will reset any values in the child table that reference them as NULL.
      • ON DELETE CASCADE: When you delete a row in the parent table, this option will cause SQL to automatically delete any records that reference it in the child table.

      For the purposes of this example, ON DELETE SET NULL doesn’t make sense. If a member leaves the club and their record is removed from the clubMembers table, their equipment is no longer available to the remaining members and should consequently be removed from the clubEquipment table. Therefore, the ON DELETE CASCADE option makes more sense for our purposes.

      To add a foreign key constraint that follows the ON DELETE CASCADE behavior, run the following ALTER TABLE statement. This creates a new constraint named newfk_ownerID which replicates the previous foreign key definition, but includes the ON DELETE CASCADE option:

      • ALTER TABLE clubEquipment
      • ADD CONSTRAINT newfk_ownerID
      • FOREIGN KEY (ownerID)
      • REFERENCES clubMembers(memberID)
      • ON DELETE CASCADE;

      Output

      Query OK, 7 rows affected (0.07 sec) Records: 7 Duplicates: 0 Warnings: 0

      This output indicates that it impacted all seven remaining rows in the clubEquipment table.

      Note: Instead of altering a table’s definition to change how a foreign key handles DELETE operations, you can define this behavior from the start in the CREATE TABLE statement like this:

      • CREATE TABLE clubEquipment (
      • equipmentID int AUTO_INCREMENT PRIMARY KEY,
      • equipmentType varchar(30),
      • brand varchar(15),
      • ownerID int,
      • CONSTRAINT fk_ownerID
      • FOREIGN KEY (ownerID) REFERENCES clubMembers(memberID)
      • ON DELETE CASCADE
      • );

      Following that, you’ll be able to delete any record from the clubMembers table, and any row in the clubEquipment table that references it will also be deleted:

      • DELETE FROM clubMembers
      • WHERE memberID = 6;

      Output

      Query OK, 1 row affected (0.00 sec)

      Although this output says it only affected one row, it will have also deleted any equipment records in the clubEquipment table that list their ownerID value as 6.

      Conclusion

      By reading this guide, you learned how to delete data from one or more tables using the DELETE statement. You also learned how SQL handles DELETE operations that conflict with foreign key constraints, and how to change that default behavior.

      The commands outlined here should work on any database management system that uses SQL. Keep in mind that every SQL database uses its own unique implementation of the language, so you should consult your DBMS’s official documentation for a more complete description of how it handles the DELETE statement and what options are available for it.

      If you’d like to learn more about working with SQL, we encourage you to check out the other tutorials in this series on How To Use SQL.



      Source link

      How To Add and Delete Users on CentOS 8


      Introduction

      When you first start using a fresh Linux server, adding and removing users is often one of first things you’ll need to do. In this guide, we will cover how to create user accounts, assign sudo privileges, and delete users on a CentOS 8 server.

      Prerequisites

      This tutorial assumes you are logged into a CentOS 8 server with a non-root sudo-enabled user. If you are logged in as root instead, you can drop the sudo portion of all the following commands, but they will work either way.

      Adding Users

      Throughout this tutorial we will be working with the user sammy. Please susbtitute with the username of your choice.

      You can add a new user by typing:

      Next, you’ll need to give your user a password so that they can log in. To do so, use the passwd command:

      You will be prompted to type in the password twice to confirm it. Now your new user is set up and ready for use!

      Note: if your SSH server disallows password-based authentication, you will not yet be able to connect with your new username. Details on setting up key-based SSH authentication for the new user can be found in step 5 of Initial Server Setup with CentOS 8.

      Granting Sudo Privileges to a User

      If your new user should have the ability to execute commands with root (administrative) privileges, you will need to give them access to sudo.

      We can do this by adding the user to the wheel group (which gives sudo access to all of its members by default).

      Use the usermod command to add your user to the wheel group:

      • sudo usermod -aG wheel sammy wheel

      Now your new user is able to execute commands with administrative privileges. To do so, append sudo ahead of the command that you want to execute as an administrator:

      You will be prompted to enter the password of the your user account (not the root password). Once the correct password has been submitted, the command you entered will be executed with root privileges.

      Managing Users with Sudo Privileges

      While you can add and remove users from a group with usermod, the command doesn’t have a way to show which users are members of a group.

      To see which users are part of the wheel group (and thus have sudo privileges), you can use the lid command. lid is normally used to show which groups a user belongs to, but with the -g flag, you can reverse it and show which users belong in a group:

      Output

      centos(uid=1000) sammy(uid=1001)

      The output will show you the usernames and UIDs that are associated with the group. This is a good way of confirming that your previous commands were successful, and that the user has the privileges that they need.

      Deleting Users

      If you have a user account that you no longer need, it’s best to delete it.

      To delete the user without deleting any of their files, use the userdel command:

      If you want to delete the user’s home directory along with their account, add the -r flag to userdel:

      With either command, the user will automatically be removed from any groups that they were added to, including the wheel group if applicable. If you later add another user with the same name, they will have to be added to the wheel group again to gain sudo access.

      Conclusion

      You should now have a good grasp on how to add and remove users from your CentOS 8 server. Effective user management will allow you to separate users and give them only the access that is needed for them to do their job.

      You can now move on to configuring your CentOS 8 server for whatever software you need, such as a LAMP or LEMP web stack.



      Source link