Trending December 2023 # How Does Linux Uniq Command Work? # Suggested January 2024 # Top 14 Popular

You are reading the article How Does Linux Uniq Command Work? updated in December 2023 on the website Moimoishop.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How Does Linux Uniq Command Work?

Introduction to Linux uniq

Linux uniq command-line utility is helpful to filter out the repeated or duplicate records in the file. In other words, it will detect the adjacent duplicate lines and omit/delete the duplicate lines from the inputs data or file.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

This utility was written by Richard M. Stallman and David MacKenzie.

Syntax:

uniq [ OPTION ] ... [ INPUT [ OUTPUT ] ] How does Linux uniq Command work?

The Linux uniq command is like a filter program, and it will use after the sort. The uniq command will get the repeated or duplicate input data or input file. With the help of different filter actions or keywords available in the uniq. We will filter out the adjacent data or duplicate data from the input file and process the end result to the output file.

Note: It will filter out the adjacent duplicate data only. If the number of duplicate records comes in serially, then only it will filter out and remove the duplicate records. Consider it as a single record. If the same record will come in the input file (without duplicate) but in a different location (except the previous adjacent location), then it will print in the output file. The duplicate data exactly match with each other, i.e. it is case sensitive.

Examples to Implement Linux uniq Command

Examples to implement the Linux uniq command are given below:

1. Uniq Command

The uniq command will help to remove the duplicate data or records from the input file.

uniq contents.txt

Explanation: We have the sample text file “contents.txt”. It has some data in the same file (refer to screenshot 1 . Now we are using the uniq command to filter out the duplicate data (refer to screenshot 1 ).

Output:

2. Uniq Count Command

In the uniq count command, we will identify how many times the line was repeated in the input file or data with prefix value. To count the number of duplicate records in the input file, we can use the “-c” option with the uniq command.

uniq -c contents.txt

Explanation: In the chúng tôi file, there are a total of 8 records in it. The non-duplicate records are three. With the help of the “-c” option, we will get the number of duplicate count record information.

Output: 

3. Uniq Repeated Command

It will display or print the unique records from the input file. No repeated or duplicate records will display. For repeated records, we can use the “-d” option with the uniq command.

uniq -d contents.txt

Explanation: From the input file (contents.txt), we will only identify the repeated unique records.

Output:

4. Uniq all-repeated

With the help of all-repeated commands, we will be able to get all the records from the input file. For all-repeated records, we can use the “-D” option with the uniq command.

uniq -D contents.txt

Output:

5. Uniq Unique Command

The unique command will help to identify the unique records or data from the input file. For unique records, we can use the “-u” option with the uniq command.

uniq -u cont.txt

Explanation: In the input file “cont.txt”, we have only one unique word in the file, i.e. “thanks”. With the help of the “-u” unique option, we are able to identify from the input data or file.

Output:

6. Uniq Using –f N Command

This uniq command, it will allow the “N” fields to be skipped while comparing the uniqueness of the lines.

Note: In the input file, it is not mandatory the number of records or input data should start with the numbered sequence.

uniq -f 3 cont.txt

Explanation: In chúng tôi input file having the number of input records (refer the screenshot 3 (a)). We are able to print the unique records with the interval of “1” (“N”) [the “N” value is depending on the client requirement]

Output:

7. Uniq Using –s N Command

The uniq –s N command is similar to the -f N option. But it will skip the “N” characters but not skip the “N” fields.

uniq -s 3 cont.txt

Explanation: In the chúng tôi input file, we are having multiple lines with special characters and numbers in it (refer to screenshot 1). With the help of the “-s” option, you will skip the special characters or numbers from the input file. The “N” denotes the number value. The same number of values will help to skip the special character from the input file.

Note: As per the “N” value, the number of characters will skip. Then after the uniq command will omit the duplicate data or records from the input file (refer to screenshot 2).

Output:

8. Uniq Using –w N Command

The uniq –w N command is similar to skipping the characters. With the help of the uniq command, we can limit the comparison to the set number of characters (“N” value).

uniq -w 3 input.txt

Explanation: In the chúng tôi file, we are having 3 records starting to form 3 letter words, i.e. “How” (refer to Screenshot 1). With the help of the “-w” option and “N” value (3), we will skip the initial 3 characters of the input file and having a character sequence (refer to Screenshot 2).

Output:

Conclusion

We have seen the uncut concept of “Linux uniq” with the proper example, explanation, and command with different outputs. The uniq command is like a filter program. It will filter out the data as per user requirements. The filter data or output data will further use of shell jobs and other application development tasks.

Recommended Articles

We hope that this EDUCBA information on “Linux uniq” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading How Does Linux Uniq Command Work?

How Does Linux Read Command Work With Examples

Introduction to Linux Read Command

In the Linux ecosystem, the read command is used to read from the file descriptor. In other words, the read command is mostly used in the bash environment. In bash, the read command is used for the word segmentation of the string under the Linux environment. The read command is a built-in utility available in the Linux ecosystem.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

read [options] [name...]

read: We can use the read keyword in the syntax or command. It will accept the two arguments as input i.e. the options and name. As per the requirement, the read command will do the word segmentation of the string.

options: We can provide the different flags as options that are compatible with the read command.

name: The read command, the name parameter will specify to store the actual words from the split operation.

How Does Linux Read Command Work?

Basically the read is a built command in the Linux environment. It has come with the basic operating system packages. Hence there is no need to add any additional packages in the Linux environment.

Option Description

-l It will display all the names of Readline functions in the environment.

-p It will print the readline function names and the bindings that they can be re-read.

-P It will display the current readline function names and bindings in the environment.

-s It will print the readline key sequences bound to macros as well as the strings output. The outputs will then re-read.

-S It will print the readline key sequences bound to macros as well as the strings output.

-v It will print the readline variable names and the values. The output can be re-read.

-V It will print all the current readline variable names and values available in the environment.

Examples to Implement Linux Read Command

Below are the examples of Linux Read:

#1. Read Command

In read command, we are able to read in the user inputs. The same input we can pass to different commands or jobs. So, in the next instance, the different commands or the jobs can perform the execution operation with the read command as in input.

Note: To access the read command value, we can use or call the system variable “REPLY”.

Command:

read

Explanation: The read command can accept user input. Just we need to right the read command and enter the input message or variable value (refer screenshot 1 (a)). By default, the message will store in the system variable. When we will call the system variable “REPLY”. The entered message will display (refer screenshot 1 (b)).

Output:

echo $REPLY

#2. Read Command with variable

In the Linux environment, we are having the functionality to access the read command value in different variables. As per the requirement, we can define the variable in the read command.

Note: there is no need to call the system generated variable “REPLY”.

Command:

read variable1

Explanation: As per the above read command, we are forcefully using the own variable to store the input value (refer screenshot 2 (a)). The same variable will use to see the read command message (refer screenshot 2 (b)).

Note: Here the read command message will not store in the “REPLY” variable.

Output:

echo "$variable1"

#3. Read Command in Shell Mode

Command:

echo "Which topic is it?";read a;echo "Welcome to $a"

Explanation: In live shell mode, we can also use the read command. It will ask the user input. Once the user will enter the input value. It will print the message as per the read command output.

Output:

#4. Read Command with “-p” Option

In read command, we are having the functionality to provide the hint while entering the user inputs in the shell prompt. For providing any hint on the shell, we need to use the “-p” option with the read command.

Command:

read -p "Please Enter Your Mobile No : "

Explanation: As per the above command, we are giving hit to the end-user for entering the relevant character. It will help to give an important message while entering any user input.

Output:

#5. Read Command with “-n” Option

In read command, we are having the functionality to restrict the specific number of characters. For restricting the number of characters, we need to use the “-n” option with the read command.

read -n 6 -p "Enter Pin Code : "

Explanation: In the above command, we are restricting the user input with a specific threshold (we have used the 6 characters). If the character will excide more than 6 then the prompt will automatically vanish.

Output:

#6. Read Command with “-s” Option

In read command, we can secure sensitive data. While entering critical information, we can hide the information. To secure the critical information, we need to use the “-s” option with the read command.

Command:

read -s -p "Enter Password : "

Explanation: As per the above read command, we are accepting the user input in a secure way. The user input will not display on screen but the read command is accepting user input.

Output :

Conclusion

We have seen the uncut concept of “Linux Read Command” with the proper example, explanation, and command with different outputs. The read command is widely used in shell and application-level jobs. We can use the read command in different ways like accepting user inputs, secure input, character restriction, input hint, etc.

Recommended Article

We hope that this EDUCBA information on “Linux Read” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does Rsync Work In Linux With Example?

Introduction to Linux Rsync

Rsync is a utility in the command line which enables users to transfer and synchronize files efficiently between a computer and an external hard drive in the entire connected network. This utility is achieved by comparison of modification times and also the file size. This utility of the synchronization is written in C language, and this application executes as a single-threaded application. Another term you would hear a lot when someone talks about rsync is that this utility is a delta encoding. Delta encoding essentially a way of storage or transmission of data as a difference of the files or, in other terms, sequential data. This utility needs to be set up between the user and the host, and once the sync is set, thus utility will itself determine parts of the local file that needs to be transferred between them to keep the sync. In this topic, we are going to learn about Linux Rsync.

Start Your Free Software Development Course

Syntax

Before we even jump into understanding what scenarios rsync would help or the working principle of rsync, it is beneficial to understand the syntax behind the rsync. Then, while going through the working principle, we can keep the syntax in mind.

OR

The usage of any of the above syntax solely lies in the developer’s level of comfortability and confidence. Therefore, there is no benefit difference in using any syntax over the other. If you notice carefully, the difference only lies in the way the source address is mentioned, and each individual has their level of confidence on which one to be used, and hence the utility in the corresponding ways.

Here, SOURCE is the place where the files or directory will be copied from, and DESTINATION is the place where the files and directories get copied into. Now, these 2 parameters or arguments are the mandatory ones, whereas the ones in square brackets “[]” are optional and can be used as per the requirement of the functionality being developed. Next, we will talk about the majority of the options which are used extensively in the industry nowadays.

How does rsync work in Linux?

In the introduction, we already learned that rsync is a command-line utility that helps in synchronizing Unix clients present in the network. This utility comes in very handy in scenarios like backing up the files in a system to another system which is housed only for backing up the files. Rsync utility also has the capability to run in daemon mode, a mode that allows the application to run in the background rather than run under the active control of a user. Daemon mode out of scope for this article, but as an interesting fact, the syntax is read as: rsync://

From here, we will look at different OPTIONS we talked about in the syntax one by one, and we will try to accompany each OPTION or a combination of OPTIONS with a code snippet and the output that is expected corresponding to it!

OPTION Where will it be used?

-v, –verbose This option is used if the user wants to know what exactly the computer is doing while executing the command.

-q, –quiet If the user doesn’t need the output message, this option can be used for suppressing the outputs.

-a, –archive This option can be used to archive files when synchronization is taking place.

-r, –recursive For recursively syncing the files and directories, this option can be used.

-b, –backup While the synchronization is taking place, if the backup of the files or delta is needed, even if there is a loss in communication, data leakage can be minimized.

-u, –update If the user doesn’t want the files at the destination to not update if the files there are newer than the source, this option can be used to successfully implement the use case.

-l, –links This option is used in scenarios where symbolic links (symlinks) should be copied as symlinks only.

-n, –dry-run This option is used when we would need to do a trial run without actual synchronization. This is done so that we understand the use case we are trying to solve and if the solution implemented actually caters to the problem.

-e, –rsh=COMMAND When this option is used, an alternative remote shell program is used for communication between the remote and local copies.

-z, –compress To minimize the data consumption during synchronization, this option can be used to compress the file being sent.

-h, –human-readable To display the output in a human-readable format for interpretation, this option is used.

–progress When the sync’s progress needs to be shown as an output, this option comes in very handy!

–remove-source-files In some cases, one would like to delete the file at the source so that there is no duplication of the files and space can be kept optimized. This is the option to get that utility!

Examples of Linux Rsync Example #1

LOCAL COPY OR SYNC OF FILES

Code:

mkdir backup ls -l ./backup/ rsync -zvh chúng tôi ./backup/ ls -l ./backup/

Output:

In this scenario, we have utilized the combination of options listed above to have a verbose (-v) output during the rsync execution. In the highlighted version, the output is changed to a more human-readable format (-h). Also, during transfer, the text file was zipped (-z) so that the data transfer can be optimized to the maximum.

Example #2

Code:

ls -l rsync -zvh--remove-source-files chúng tôi ./backup/ ls -l

Output:

In the case of, we see that chúng tôi was present in the working directory in the initial instance. After the synchronization is complete, when we do an ls command, we see that the file has been moved from there to the new location as specified in the command, i.e. Backup.

Conclusion

In this article, we have gone through various options that are possible through the use of rsync in general. In cases of performing rsync on different IPS, only the user and the IP address of systems need to be added extra to complete the utility.

Recommended Articles

We hope that this EDUCBA information on “Linux Rsync” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

How Does An Nft Work?

Online space is abuzz with talk of NFTs. However, as is the case with any new thing, especially when it involves the transfer of money and property, digital or physical, non-fungible tokens operate in a sphere that may seem foggy and confusing to those on the outside.

Whenever there is an explosion of cryptocurrency news, most people tend to wait until the hype subsides to see if there was any real substance propelling the whole thing forward. But the nature of the NFT phenomenon warrants some understanding, for, chances are that you may be able to benefit from it, or, at the least, understand what impact it can have on our lives.

Here are the basics of how an NFT works, and what the craze is all about. 

Related: 10 Weirdest NFT Crypto Art For Sale Right Now

NFT characteristics

Non-Fungible Tokens are assets that correspond to a physical or digital item that is unique and is set apart by others of its kind. Owning an NFT is not unlike owning a collectible or an artwork. There is a wide class of NFTs, like paintings, music, Pokemon cards, and even tweets. And just about anything in the world can come under this umbrella. 

Other than being a one-of-a-kind entity, NFTs are also indestructible. This is because all of their data is stored on a blockchain which makes copying or destroying them (almost) impossible. On top of that, when you own an NFT, it is you who actually owns it, not the companies that created them. This is unlike the music that you listen to on Spotify or iTunes, or the games you get on Steam, which you don’t own per se. 

And because NFT ownership data is stored on the blockchain, the items can be traced back to the creator allowing easy authentication without involving a third-party. So, there’s never a dispute over ownership of the material. 

The Importance of NFTs

The boom in NFTs is tied to cryptocurrency users and the potential for a revolution in the digital collectibles and gaming space. In fact, a whopping $423 million have been spent on NFTs so far, a number that is only set to grow exponentially in the coming weeks and months. 

The growth can be attributed to the blockchain technology behind it since it gives owners full rights to their unique assets (and even gives them the opportunity to make money off of it). In fact, people also sell digital merchandise that they acquire in-game such as decals, stickers, costumes, and game currency on other markets.

But artists stand to gain the most from NFTs, or so it’s been claimed by NFT proponents. The most popular instance of this is Grimes, who sold her digital art for $6 million as NFTs. Of course, this is an extreme example and only artists that have already made it big can bag such huge sums of money from die-hard ostensibly rich fans.

But those who want to support local artists can do so with NFTs as well. Their artwork can be sold digitally to anyone anywhere in the world, without having to go to a gallery or an auction house. Furthermore, this allows them to keep a much higher profit-share from the sales. On top of that, NFTs can have royalties programmed within them, allowing the creator to receive a cut of the profit every time the artwork changes hands.  

Related: How to Make and Sell NFT Art

How do they work?

Most NFTs are part of the Ethereum blockchain and though Ethereum is a cryptocurrency, its blockchain also stores information about NFTs, which differentiates them from the ETH coin. Most of the NFT tokens are built using Ethereum token blueprints for easy compatibility with the ecosystem as a whole. But Ethereum isn’t the only blockchain to host NFTs. There are many other blockchains that have also started implementing their own NFT token standards, such as Tron, Neo, and Eos. 

There are dozens of NFT markets where you can purchase everything from rare artworks to NBA top shot clips, games, and other collectibles. A happy buyer needs only to go to the marketplace, find something worth splurging on, and bid. A creator can also submit their NFTs for others to purchase. All transactional history is kept secure thanks to the publically accessible blockchain technology.  

What makes NFTs valuable?

As is the case with any market asset, NFTs derive their value from supply and demand. The reason why some people pay such exorbitant amounts is that NFTs are in short supply, while the demand is extremely high, especially from gamers, investors, collectors, and fans. 

But NFTs are not just dead things that you buy and horde for the rest of your life. Some of them have the potential to generate profit for their owners. For instance, one investor spent more than $200,000 on a single segment of a racing track in the game F1 Delta Time which will generate 5% profit from all races that take place on it. 

NFT uses

Though still in its infancy, there is a broad range of NFT uses that could simplify ownership authentication controversies. For instance, we all can have digital as well as printed copies of Van Gogh’s Starry Night, but there is only a single original. Likewise, though there may be multiple copies of a piece of art (painting, music, etc.), only the person that has its token owns it. All the usage (as well as bragging) rights lie with that person. 

In the future, there could also be an integration between the physical and the virtual space through NFTs. Nowadays, when you buy a physical piece of art, you either have its custody or you get to keep it somewhere. But these can also be tokenized so that their digital forms also exist. Whoever owns the token, owns that physical, tangible, art as well.  

The Nifty craze

There is no telling where the nifty (as NFTs are sometimes called) craze is headed. From people spending hundreds of dollars on CryptoKitties, to entire albums being produced through NFTs (case in point – When You See Yourself by Kings of Leon who have generated $2 million from the sales so far) – who knew NFTs would take on such a massive life of their own. 

Nifty enthusiasts find it exciting to say that they own this or that unique piece of art (and potentially make money from reselling it), but how long can this bubble last? The sales are growing exponentially with each passing week and there’s doesn’t seem to be an end in sight. 

There are other concerns as well. Blockchain technologies use up a lot of electricity per transaction, and since NFTs use the same transaction framework, the increasing number of transactions is definitely going to have an impact on the environment. Many artists have even decided to not sell their NFTs after hearing about the detrimental effects that NFT transactions could have on climate change. 

Climate change will be irreversible once Pokemon releases NFTs

— Zach Leffers (@ZachLeffers) March 10, 2023

These are the basics of how NFTs work. Whether this is capitalism on steroids or the harbinger of doom, only time will tell. But at least you’re now informed.  

Related:

How Does A Wireless Mouse Work?

This article explains about a wireless mouse, its types, and how it works. So, without further delay, let us get right into it.

Before we get into the working principle of a wireless mouse, let us first discuss the two types of wireless mouse popular in the market.

A wireless USB mouse uses a USB dongle that receives data transmitted by the wireless mouse. This mouse operates in the 2.4 GHz frequency band to transfer data. Low battery consumption, connection over a longer distance, and lower latency are what make a wireless USB mouse so popular.

To use the wireless USB mouse, you simply plug the USB dongle into the computer, power on the mouse and the input device is ready to use. 

Wireless Bluetooth uses a computer’s Bluetooth to transfer data. To use a wireless Bluetooth mouse, you first need to pair it with your computer’s bluetooth. Once you pair both the devices, you can use it to move the mouse cursor.

The Bluetooth wireless mouse usually suffers from higher latency and higher battery consumption compared to the wireless mouse using USB connector. Furthermore, it also does not support connection over longer distances compared to a wireless USB mouse. 

Bluetooth also uses a 2.4 GHz frequency band to transfer data like a wireless USB mouse.

The mouse records its current position using LED or laser light.

The mouse sends this movement data to the computer using a transmitter.

The computer moves the mouse cursor using the received mouse movement data.

Three things are constantly occurring when you physically move the mouse:

Now let’s discuss each step in detail.

Most mouse nowadays uses optical sensors to record mouse movement. These optical sensors take a couple of thousand pictures every second. And then, the sensor compares each picture to the previous one to record the mouse movement. On the other hand, an older mechanical mouse uses a rubber ball to track the mouse movements.

Under the mouse, there is a LED or laser emitter, depending on the type of mouse you use. This emitter turns on the LED when you connect the mouse to a computer. 

The light touches the surface and then reflects to the mouse, where a CMOS (Complementary metal-oxide-semiconductor) sensor records the bounce-back time. By doing this, the mouse records every surface detail. 

Once the sensor records the bounce back time for a second time, the DSP (Digital Signal Processor) compares the two surface details and calculates the new mouse position. Once the mouse figures out its position, it sends the data about its position to the computer. This will then move the mouse cursor. 

Different mouse will have different frequencies that it operates on. This is why a USB dongle from one device may not always work on a different device, even if they both have the same manufacturer.

The receiver can be either a USB receiver or a Bluetooth module inside the computer. The receiver is set to catch a frequency signal in a certain range. So when the transmitter sends the signal on said radio frequency, the receiver catches the signal sent through the channel. The receiver then sends this information to the driver installed. The mouse driver in turn decodes this radio signal to determine the mouse’s position.

Some devices only support line of sight communication. This means that the computer may not record data from the mouse when there is an obstacle between the transmitter and the receiver.

Once the computer receives the data, it moves the mouse cursor according to the physical mouse movements.

In the case of a Wireless USB mouse, the receiver is the USB dongle you plug into the computer’s USB port. As for the wireless Bluetooth mouse, the mouse sends data to the PC in the frequency range between 2.402 to 2.485GHz once both the devices are connected and paired for an encryption.

Depending on the mouse, it may use a wireless receiver or Bluetooth, or both. If your mouse supports both wireless USB and Bluetooth connectivity, you do not need the USB dongle. You can simply pair it with your computer’s Bluetooth.

However, if your mouse only supports wireless USB, it requires a separate USB dongle.

Both USB and Bluetooth wireless mouse uses electromagnetic waves to transfer data from the transmitter to the receiver. These waves have high wavelength. Thus, making these radiation harmless.

How Does Laravel Permissions Work With Examples

Introduction to Laravel Permissions

Laravel is one of the most sought after frameworks for E-commerce development. The reason for this popularity being the ease of usage. Laravel allows the developer of the scope of creating complex structures and functionalities using simple and expressive syntax. Laravel is scalable and that is the reason why E-commerce site owners prefer to use it. This gives them a wide range of options to choose from for catering to demanding customers. Laravel is known for its vast library of queries which provide all that is needed for quick development. The framework is also capable of integrating with third-party queries to form standalone systems.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

One such query that makes development easy is Laravel Permissions.

What is Laravel Permission? How does Laravel Permission work?

Through Roles and Permissions, one can create several types of users with different roles and permissions, some users will only have view access, some users can also edit items, some can go ahead and delete. Access is usually provided by the Super Admin.

Example #1

Installing the tool: The migration needs to be run: PHP artisan migrate

1. The HasRole needs to be added to the User Model:

class User extends Authenticatable { use HasRoles; ... }

2. It now has to be loaded into the Tool for the Roles to be displayed:

public function tools() /* defining the function tools */ { return [ new NovaToolPermissions(), ]; }

3. Adding an additional relationship if roles are to be assigned from the User resource:

public function fields(Request $request) { return [ ... BelongsToMany::make('Role', 'role', Role::class), ]; }

4. Since we are using the Nova Tool for permission, the viewNova Gate default can be replaced with Gate():

protected function gate() { }

5. This program comes with default permissions:

"viewNova": "viewRoles": "manageRoles": "assignRoles": "viewUsers": "manageUsers":

6. It is pertinent to know that, routine permission is required for certain sections. This is to ascertain that only the correct authority has access to the sections of the blog or the whole blog.

For example, the policy related to the blog: PHP artisan make: policy BlogPolicy Now the policy needs to be assigned:

class AuthServiceProvider extends ServiceProvider { use ValidatesPermissions; protected $policies = [ ]; public function boot() { collect([ 'viewBlog', 'manageBlog', Gate::define($permission, function ($user) use ($permission) { return true; } }); }); } }

7. Final step. Access control has to be specified in the policy:

use IlluminateSupportFacadesGate; public function viewAny($user) { return Gate::any(['viewBlog', 'manageBlog'], $user); } public function view($user, $post) { return Gate::any(['viewBlog', 'manageBlog'], $user, $post); } public function create($user) { } public function update($user, $post) { } public function delete($user, $post) { } public function restore($user, $post) { } public function forceDelete($user, $post) { }

8. Now add labels:

{ "viewBlog": "View Blog", "manageBlog": "Manage Blog" }

Output:

This one is for the Edit Role:

The Role would now need to be assigned.

Example #2

Another quick example:

Install: Install it into the Laravel application which uses Nova through composer. Register the provider in case you have the package discovery disabled. It will be registered in the config/app PHP file as shown below:

NovaPermissionServiceProvider::class, ]

1. Now tool needs to be registered as shown below:

/*defining tools method */ public function tools() { return [ /*…*/ LaravelNovaPermission::make(), ]; }

2. Now, the addition of Morph To Many to the resource as follows:

use LaravelNovaFieldMorphToMany; /*defining method*/ public function field(Request $request) { return [ /* ...*/ MorphToMany::make('Role', 'role', Role::class), MorphToMany::make('Permission', 'permission', Permission::class), ]; }

3. Now, adding class ForgetCachedPermissions to the config/nova.php as follows:

/* config/nova.php */ /*Registering middleware*/ ‘web’, /*adding different classes*/ DispatchServingNovaEvent::class, Authenticate::class, Authorize::class, BootTools::class, ForgetCachedPermissions::class, ],

4. Artisan command line can be used for localization files publishing: vendor: publish. Usage of Custom Role:

/*app/Providers/NovaServiceProvider.php*/ /*defining tools method */ public function tools() { return [ /* ...*/ LaravelNovaPermission::make() ]; }

5. Changing the default Authorization (Policy-based) to Permissions based Authorisation:

/* app/Nova/MyNovaResource.php*/ class MyNovaResource extends Resource { use PermissionsBasedAuthTrait; /* defining array*/ public static $permissionsForAbilities = [ ]; } public static $permissionsForAbilities = [ ];

Output:

Here one can create Roles and give access to users as well as to others who would have defined Roles. It is imperative to remember that at the top of the Access control Hierarchy, sits the Super Admin. The Role of the Super Admin is to provide definite access control authorizations for specific responsibilities. Developers need to be careful while creating ACL or Access Control Lists, since a wrong move here may lead to jeopardizing the entire project.

Steps to Provide Laravel Permissions

Another way to provide permissions is:

Step #1

PHP artisan make: seeder PermissionSeeder

Step #2 <?PHP use IlluminateDatabaseSeeder; use SpatiePermissionModelsRole; use SpatiePermissionModelsPermission; class PermissionSeeder extends Seeder { /** * Run the database seeds. * @return void */ public function run() { $roles=[ 'admin', 'accountant', 'user' ]; $permissions=[ ]; foreach ($roles as $role) { } foreach ($authorized_roles as $role) { } } } }

Add role to the Users

Go ahead and refresh the database:

php artisan migrate: fresh –seed

Conclusion

Laravel Permission is important from the perspective of access control. An access control list is a concise set of information authorising users for a certain level of access. Laravel Permissions work on the basis of hierarchy. Developers will be given a higher level of access than front end users.

The administrator of the site will be provided with greater access. The final access rests with the Super Admin. He/she will be the one providing everyone with the Roles and their access limits.

Recommended Articles

We hope that this EDUCBA information on “Laravel Permissions” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Update the detailed information about How Does Linux Uniq Command Work? on the Moimoishop.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!