One place for hosting & domains

      Tinker with the Data in Your Laravel Apps with PHP Artisan Tinker

      Introduction

      Today we’ll talk about how to use one of Laravel’s lesser-known features to quickly read data from our Laravel applications. We can use Laravel artisan’s built-in php artisan tinker to mess around with your application and things in the database.

      Laravel artisan’s tinker is a REPL (read-eval-print loop). A REPL is an interactive language shell. It takes in a single user input, evaluates it, and returns the result to the user.

      A quick and easy way to see the data in your database.

      Wouldn’t it be nice to see the immediate output of commands like:

      
      App\User::count();
      
      
      App\User::where('username', 'samuel')->first();
      
      
      $user = App\User::with('posts')->first();
      $user->posts;
      

      With php artisan tinker, we can do the above pretty quickly. Tinker is Laravel’s own REPL, based on PsySH. It allows us to interact with our applications and stop dd()ing and die()ing all the time. You may be familiar with littering your code with print_r()s and dd()s to ascertain values at points during computation.

      Before we tinker with our application, let us create a demo project. Let’s call it ScotchTest. If you have the laravel installer installed on your computer, run this command.

      1. laravel new ScotchTest

      For those without the Laravel installer on their computer, you can still use composer to create a new Laravel project.

      1. composer create-project laravel/laravel ScotchTest --prefer-dist

      After installing our demo Laravel project, we need to create a database and set up migrations. For this article, we will be using the default Laravel migrations. So we configure our .env file to point to the database you created for this test. The default migrations include creating a users table and a password_resets table.

      From the root of the project, run

      1. php artisan migrate

      After migrating our database, we should see something similar to

      Laravel Artisan Tinker Initial Migration

      By default, Laravel provides a model factory that we can use to seed our database. Now let’s begin to tinker with our application.

      From the root of the Laravel project, run the following command.

      1. php artisan tinker

      This command opens a repl for interacting with your Laravel application. First, let’s migrate our database. While in the repl, we can run our model factory and seed our database.

      factory(App\User::class, 10)->create();
      

      A collection of ten new users should show up on your terminal. We can then check the database to see if the users were actually created.

      App\User::all();
      

      To get the total number of users in our database, we can just call count on the User model.

      App\User::count();
      

      After running App\User::all() and App\User::count(), mine looks like this. You should get something similar to mine only difference being the data generated.

      Laravel Artisan Tinker Seed Database

      From the repl, we can create a new user. You should note that we interact with this repl just like you would write code in your Laravel application. So to create a new user, we would do

      $user = new App\User;
      $user->name = "Sammy Shark";
      $user->email = "[email protected]";
      $user->save();
      

      Now we can type $user to the repl and get something like this.

      Laravel Artisan Tinker Create a New User

      To delete a user, we can just do

      $user = App\User::find(1);
      $user->delete();
      

      With tinker, you can check out a class or function documentation right from the repl. But it depends on the class or function having DocBlocks.

      1. doc <functionName>

      Calling doc on dd gives us this.

      Laravel Artisan Tinker Read a Function

      We can also check out a function or class source code while in the repl using

      1. show <functionName>

      For example, calling show on dd gives us this.

      Laravel Artisan Tinker Check a Source

      Laravel Tinker is a tool that can help us easily interact with our application without having to spin up a local server. Think of a simple feature you want to test in a couple of lines you’d delete from your project, use tinker instead.

      Getting Started with Redis in PHP

      Introduction

      Salvatore Sanfilippo is an open-source, in-memory data structure server with advanced key-value cache and store, often referred to as a NoSQL database. It is also referred to as a data structure server since it can store strings, hashes, lists, sets, sorted sets, and more.

      The essence of a key-value store is the ability to store some data, called a value inside a key. This data can later be retrieved only if we know the exact key used to store it.

      Salvatore Sanfilippo (creator of Redis) said Redis can be used to replace an RDBMS database. Now, although nothing is impossible, I think it would be a bad idea because using a key-value store for things, like a full-text search, might be painful. Especially, when you consider ACID compliance and syncing data in a key-value store: painful.

      Below are just a few uses of Redis, though there are many more than this.

      • Caching can be used in the same manner as memcached.
      • Leaderboards or related problems.
      • Counting stuff.
      • Real-time analysis.
      • Deletion and filtering.
      • Show latest item listings on your home page.

      This article’s aim is not to show you the syntax of Redis (you can learn about Redis’s syntax here), in this article, we will learn how to use Redis in PHP.

      Redis is pretty easy to install and the instructions, included, are for both Windows and Linux users.

      To install Redis on Linux, is pretty simple, but you’ll need TCL installed if you don’t have TCL installed. You can simply run:

      1. sudo apt-get install tcl

      To install Redis:

      1. wget http://download.redis.io/releases/redis-2.8.19.tar.gz
      2. tar xzf redis-2.8.19.tar.gz
      3. cd redis-2.8.19
      4. make

      Note: 2.8.19 should be replaced with the latest stable version of Redis.

      All Redis binaries are saved in the src Folder. To start the server:

      1. src/redis-server

      Redis installation on Windows is very easy, just visit this link, download a package, and install.

      Install Predis a Redis Client for PHP

      Predis is a Redis Client for PHP. It is well written and has a lot of support from the community. To use Predis just clone the repository into your working directory:

      1. git clone git://github.com/nrk/predis.git

      First, we’ll require the Redis Autoloader and register it. Then we’ll wrap the client in a try-catch block. The connection setting for connecting to Redis on a local server is different from connecting to a remote server.

          <?php
          require "predis/autoload.php";
          PredisAutoloader::register();
      
          try {
              $redis = new PredisClient();
      
              
              
          }
          catch (Exception $e) {
              die($e->getMessage());
          }
      

      Now that we have successfully connected to the Redis server, let’s start using Redis.

      Redis supports a range of datatypes and you might wonder what a NoSQL key-value store has to do with datatypes? Well, these datatypes help developers store data in a meaningful way and can make data retrieval faster. Here are some of the datatypes supported by Redis:

      • String: Similar to Strings in PHP.
      • List: Similar to a single dimensional array in PHP. You can push, pop, shift and unshift, the elements that are placed in order or insertion FIFO (first in, first out).
      • Hash: Maps between string fields and string values. They are the perfect data type to represent objects (e.g.: A User with a number of fields like name, surname, and so forth).
      • Set: Similar to list, except that it has no order and each element may appear only once.
      • Sorted Set: Similar to Redis Sets with a unique feature of values stored in set. The difference is that each member of a Sorted Set is associated with score, used to order the set from the smallest score to the largest.

      Others are bitmaps and hyperloglogs, but they will not be discussed in this article, as they are pretty dense.

      In Redis, the most important commands are SET, GET and EXISTS. These commands are used to store, check, and retrieve data from a Redis server. Just like the commands, the Predis class can be used to perform Redis operations by methods with the same name as commands. For example:

          <?php
          
          $redis->set(';message';, ';Hello world';);
      
          
          $value = $redis->get('message');
      
          
          print($value);
      
          echo ($redis->exists('message')) ? "Oui" : "please populate the message key";
      

      INCR and DECR are commands used to either decrease or increase a value.

          <?php
          $redis->set("counter", 0);
      
          $redis->incr("counter"); 
          $redis->incr("counter"); 
      
          $redis->decr("counter"); 
      

      We can also increase the values of the counter key by larger integer values or we can decrease the value of the counter key with the INCRBY and DECRBY commands.

          <?php
          $redis->set("counter", 0);
      
          $redis->incrby("counter", 15); 
          $redis->incrby("counter", 5);  
      
          $redis->decrby("counter", 10); 
      

      There are a few basic Redis commands for working with lists and they are:

      • LPUSH: adds an element to the beginning of a list
      • RPUSH: add an element to the end of a list
      • LPOP: removes the first element from a list and returns it
      • RPOP: removes the last element from a list and returns it
      • LLEN: gets the length of a list
      • LRANGE: gets a range of elements from a list

      Simple List Usage:

          <?php
          $redis->rpush("languages", "french"); 
          $redis->rpush("languages", "arabic"); 
      
          $redis->lpush("languages", "english"); 
          $redis->lpush("languages", "swedish"); 
      
          $redis->lpop("languages"); 
          $redis->rpop("languages"); 
      
          $redis->llen("languages"); 
      
          $redis->lrange("languages", 0, -1); 
          $redis->lrange("languages", 0, 1); 
      

      A hash in Redis is a map between one string field and string values, like a one-to-many relationship. The commands associated with hashes in Redis are:

      • HSET: sets a key-value on the hash
      • HGET: gets a key-value on the hash
      • HGETALL: gets all key-values from the hash
      • HMSET: mass assigns several key-values to a hash
      • HDEL: deletes a key from the object
      • HINCRBY: increments a key-value from the hash with a given value.
          <?php
          $key = ';linus torvalds';;
          $redis->hset($key, ';age';, 44);
          $redis->hset($key, ';country';, ';finland';);
          $redis->hset($key, 'occupation', 'software engineer');
          $redis->hset($key, 'reknown', 'linux kernel');
          $redis->hset($key, 'to delete', 'i will be deleted');
      
          $redis->get($key, 'age'); 
          $redis->get($key, 'country')); 
      
          $redis->del($key, 'to delete');
      
          $redis->hincrby($key, 'age', 20); 
      
          $redis->hmset($key, [
              'age' => 44,
              'country' => 'finland',
              'occupation' => 'software engineer',
              'reknown' => 'linux kernel',
          ]);
      
          
          $data = $redis->hgetall($key);
          print_r($data); 
          
      

      The list of commands associated with sets includes:

      • SADD: adds a N number of values to the key
      • SREM: removes N number of values from a key
      • SISMEMBER: if a value exists
      • SMEMBERS: lists of values in the set.
          <?php
          $key = "countries";
          $redis->sadd($key, ';china';);
          $redis->sadd($key, ['england', 'france', 'germany']);
          $redis->sadd($key, 'china'); 
      
          $redis->srem($key, ['england', 'china']);
      
          $redis->sismember($key, 'england'); 
      
          $redis->smembers($key); 
      

      Since Redis is an in-memory data store, you would probably not store data forever. Therefore, this brings us to EXPIRE, EXPIREAT, TTL, PERSIST:

      • EXPIRE: sets an expiration time, in seconds, for the key after which it is deleted
      • EXPIREAT: sets an expiration time using UNIX timestamps for the key after which it is deleted
      • TTL: gets the remaining time left for a key expiration
      • PERSIST: makes a key last forever by removing the expiration timer from the key.
          $key = "expire in 1 hour";
          $redis->expire($key, 3600); 
          $redis->expireat($key, time() + 3600); 
      
          sleep(600); 
      
          $redis->ttl($key); 
      
          $redis->persist($key); 
      

      The commands listed in this article are just a handful of many existing Redis commands (see more redis commands).

      Future of Redis

      Redis is a better replacement for memcached, as it is faster, scales better (supports master-slave replication), supports datatypes that many (Facebook, Twitter, Instagram) have dropped memcached for Redis. Redis is open source and many brilliant programmers from the open-source community have contributed patches.

      Other sources

      How to Learn PHP… Fast


      PHP is a programming language that has a relatively simple but versatile syntax, making it a great starting point for beginners. However, you might still be overwhelmed by the thought of implementing PHP code for the first time.

      Fortunately, there are plenty of free resources you can use to learn PHP. Whether you watch a few YouTube tutorials or take an online course, you can quickly become familiar with this popular programming language.

      In this post, we’ll introduce you to PHP and explain the benefits of learning it. Then, we’ll show you some easy ways to get started. Ready to dive in?

      An Introduction to PHP

      PHP (PHP: Hypertext Preprocessor) is a server-side scripting language used in web development. It’s currently used on 77.6% of websites, including Facebook, Wikipedia, and Instagram:

      php official website

      Like WordPress, PHP is open-source. Originally, it was used simply to build a personal homepage. However, since its creation in 1994, PHP has evolved to accommodate more dynamic websites.

      The first thing you need to know about PHP programming is that it happens on the server. When someone tries to visit your website, your server will process its PHP code before sending any information to the browser.

      This is what makes PHP different from other scripting languages. If you’re writing HTML or CSS, this code will affect the information visitors see in a browser. However, PHP code is processed before the content loads.

      For example, a PHP script can be used as a source code for HTML. Here’s what the original PHP script can look like:

      <html>
      <head>
       <title>PHP Test</title>
      </head>
      <body>
      <?php echo '<p>Hello World</p>'; ?>
      </body>
      </html>

      In HTML, this will create the following output:

      <html>
      <head>
       <title>PHP Test</title>
      </head>
      <body>
      <p>Hello World</p>
      </body>
      </html>

      When visitors view your website, they will see the “Hello World” message in their web browser. Although PHP is powered by HTML, front-end viewers will only experience the HTML output.

      How PHP Works in WordPress

      If you download WordPress, you’ll notice that many of the files are written in PHP. This is because PHP code is the framework for the WordPress software:

      php files for WordPress

      After creating a WordPress website, your site files are stored in a MySQL database. This contains all your website’s data, including your posts, plugins, and themes.

      When someone clicks on your site link, their browser sends a request to your server. In WordPress, the server has to process PHP code to create HTML pages. Then, it can send the HTML code back to the visitor’s browser.

      Similar to other programming languages, PHP has several versions. If you’re using an outdated version, you won’t receive important bug fixes or security updates.

      As a WordPress user, it’s important to make sure to update your PHP version. WordPress recommends using PHP version 7.4 or greater. This can be the key to keeping your website fast and secure.

      Other than updating the PHP version, some website owners may never touch this code. Since WordPress comes with built-in PHP files, you likely won’t need to learn this programming language to manage your website. That being said, there are many reasons why you may want to consider becoming an expert PHP coder.

      Why You Might Want to Consider Learning PHP

      Since PHP usage has been slowly declining in recent years, you might be wondering if it’s worth learning it. Although fewer websites have been using PHP, it remains the most popular server-side programming language. Plus, it is still a vital part of many Content Management Systems (CMSs).

      In WordPress, PHP is the fundamental language behind all plugins and themes. When you want to modify these tools, you’ll likely need to use PHP coding.

      Plus, PHP is easy to learn. Its syntax is similar to HTML and even uses some embedded HTML in its code. Since you can reuse blocks of code and built-in functions, PHP is one of the simplest programming languages.

      Here are some additional advantages of learning PHP:

      • It’s free and open-source.
      • It integrates with popular databases like MySQL, Oracle, Sybase, PostgreSQL, and more.
      • It supports most web browsers.
      • It offers consistent updates to enhance security, performance, and support.

      If you want to become a web developer, it’s important to learn PHP. When creating new WordPress plugins and themes, you’ll need to know how to build and edit PHP files.

      Once you become familiar with this language, you can eventually become a PHP developer. In this position, you can write scripts to create and modify software for your clients.

      However, knowing PHP can also help you pursue other career paths, such as:

      • Cybersecurity
      • Information Technology (IT)
      • Back-end and full-stack development

      As you progress through your career in PHP development, you can look for higher-paying positions like software development management. You can even pursue directorial roles and become an information technology director.

      How to Learn PHP Fast (5 Methods)

      Although you could gain a college degree in web development, this can be an expensive option. Luckily, there are plenty of ways you can learn how to code online, without having to pay a penny. Let’s look at how you can become an expert in PHP, for free.

      1. Watch a YouTube Tutorial

      If you’re looking to learn a new skill, one of the best online resources is YouTube. By watching in-depth guides from expert coders, you can easily become familiar with PHP programming.

      Unlike other social media sites, YouTube tends to highlight the most popular videos, rather than the most recent ones. If you watch a tutorial that was published years ago, you could receive outdated information.

      To narrow your results, you can click on Filters at the top of the page. Next, select a recent upload date. You can choose your desired video length as well:

      youtube search php tutorial

      Then, you can find a video that suits your needs. One of the most popular PHP tutorials is PHP For Beginners by Traversy Media. This outlines the fundamentals of PHP:

      In this YouTube video, you can use timestamps to skip to an area you want to learn. If you watch the entire three-hour tutorial, you can learn everything about PHP, including functions, loops, arrays, and more. By following along with the voiceover, you can create your first PHP/MySQL project.

      You can also watch PHP Tutorial for Beginners – Full Course by Envato Tuts+. This is a more detailed PHP guide that takes you from an absolute beginner to an expert coder:

      envato tuts youtube learn php

      The instructor, Jeremy McPeak, starts with the basics, showing you everything you need to learn as a beginner. Then, he teaches you about variables, syntax, and how to make decisions in your code. By the end of the video, you’ll be able to write your own functions and respond to GET and POST requests.

      When you search for PHP tutorials on YouTube, you can find thousands of free videos to watch. With this method, you can watch coding in real-time rather than reading a static web page.

      2. Take an Online Course

      If you want to receive a more in-depth explanation of PHP, you can sign up for an online course. Although it can take longer to complete course modules, this can lead to a more thorough education in programming.

      Codecademy

      Whether you’re trying to prepare for a career in web development or just learning programming languages as a hobby, you can learn how to code on Codecademy. This platform provides the free Learn PHP course, which has been taken by over 45 million people:

      Codeacademy learn php

      In 25 hours, you’ll receive a comprehensive overview of PHP, including variables, functions, arrays, loops, and more. Each module has instructions on how to immediately implement what you’ve learned:

      Codeacademy learn php exercise

      Once you follow the instructions and enter the correct coding, you can continue to the next lesson. If you need help, you can always use a hint:

      Codeacademy php exercise

      At any point, you can review key concepts using the cheatsheet. You can also browse the Codecademy community forums for that module. These links are provided at the end of each exercise:

      Codeacademy php concept review forums

      Since PHP interacts with HTML, you’ll likely need to know the basics of HTML before taking this course. Fortunately, Codecademy has a Learn HTML course that you can take beforehand.

      Udemy

      Another place to find PHP courses is Udemy. Here, you can join over six million users and start expanding your coding skills. Unlike Codecademy, Udemy contains many different PHP courses, so you can find the one that best suits your needs:

      udemy php courses

      With over 22,000 reviews, the most popular PHP course on Udemy is called PHP for Beginners. In this program, you can watch 37 hours of educational videos and obtain a certificate once you’re finished:

      udemy php for beginners course

      If you’re completely new to coding, this Udemy course takes you through the basics of PHP, as well as Object Oriented PHP and MySQLi. You’ll learn about custom functions, PHP security, control structures, and much more. It also teaches you how to create a content management system similar to WordPress or Joomla.

      3. Review the PHP Manual

      You can also learn the best practices of the PHP language straight from the creators themselves. In the official PHP manual, you’ll gain installation instructions, syntax advice, and Frequently Asked Questions (FAQs) from other emerging developers.

      When you first open the manual, you can read an overview of PHP and what it does. This will also list compatible operating systems and databases:

      php manual what is php

      Then, you can follow the installation and configuration guide. Depending on your operating system, you’ll see some requirements and best practices on how to get started:

      php manual how to install and configure

      One of the most helpful sections of this manual is the Language Reference. Here, you’ll find a list of outbound links about basic PHP syntax and how to start writing your own code:

      php manual language reference

      Similar to online courses, you can read how-to guides about variables, functions, operators, and much more. You’ll even learn how to handle PHP errors when they happen:

      php manual basics

      This manual also gives you information about PHP security. You can read about possible attacks, as well as error reporting:

      php manual security overview documentation

      As you become more knowledgeable in PHP, you can keep this manual for future reference. For example, you might need to look up certain functions to implement them properly:

      php manual function reference

      However, the PHP manual may not be the best option for beginners. Although its information is valuable and straightforward, it doesn’t include any interactive exercises. You’re likely better off using this as a reference during the learning process.

      4. Read a Book

      If you’re a visual learner, one way to learn PHP is by reading a book. Whether you find an online publication or go to your local library, you can find valuable information about the PHP programming language.

      PHP Apprentice is an online book that you can access for free. You can use this open-source reading material to start understanding PHP and its practices:

      php apprentice overview

      Using the table of contents, you can find a specific topic about PHP. For each chapter, there will be written explanations along with examples of coding:

      php apprentice module

      Plus, PHP Apprentice is a book that is constantly evolving. By giving feedback on its GitHub repository, you can request certain topics or more in-depth explanations:

      php apprentice code

      When learning a new skill like PHP, it can often be more convenient to read an e-book because they’re readily available online. However, you can also use your local library.

      On your library’s website, you can search its database for PHP books. Then, you can place a hold on the ones you want to read:

      learn php book recommendations

      Some libraries even let you check out e-books using an app like CloudLibrary or OverDrive. This way, you can get your hands on library books without ever leaving your home.

      Although the library can be a valuable resource for free books, you may not find the most up-to-date information. If you decide this method is right for you, you’ll want to look for books that were published in the last few years. This way, you’re not learning an outdated PHP version.

      5. Try an Interactive Tutorial

      Rather than signing up for an educational course in PHP, you can walk yourself through online tutorials. You don’t have to pay for the learning material or even create an account – you can simply open the website and start learning at your own pace. Let’s look at some options.

      W3Schools

      W3Schools is one of the best resources for free coding tutorials. On this platform, you can learn the basics of PHP, CSS, HTML, JavaScript, and much more.

      When you click on its PHP guide, you’ll notice that there are tons of free modules to explore:

      php tutorial introduction to php

      In the introductory sections, W3Schools will outline the basic concepts of PHP, as well as everything you need to get started:

      php tutorial php installation

      When you dive into the learning modules, you can read detailed explanations about syntax, variables, operators, regular expressions, and any other PHP concept. You’ll also see coding examples on each page:

      php tutorial syntax

      By clicking on Try it Yourself, you can open a code editor in a new tab. Here, you can implement changes to the existing code and see how it’ll look on the front end:

      w3schools coding exercise

      Once you grasp the basics, you can learn more advanced concepts. W3Schools will show you how to create forms with data validation. You’ll also learn how to use PHP with Object-Oriented Programming, a MySQL database, XML parsers, and AJAX.

      When you feel comfortable with what you’ve learned, you can test your skills with quizzes and exercises:

      w3schools learn php quiz

      This can help you remember what you’ve studied. Plus, you can check whether you need to revise certain concepts and go back to those modules if needed.

      Learn-php.org

      If you want to learn PHP with a simple but effective interface, you can try the interactive tutorial on learn-php.org. Although this won’t turn you into a developer, you can use it to understand how PHP works:

      learn-php.org tutorial

      In just 11 modules, you’ll learn about variables, arrays, strings, loops, functions, and more. Like some other options on this list, learn-php.org includes simple explanations of concepts, followed by coding examples:

      php simple arrays

      At the bottom of the page, you can perform an exercise to test your knowledge. For example, you may have to create a new array in PHP:

      learn-php.org exercise

      Although learn-php.org doesn’t have a lot of modules yet, it is constantly being updated. Using its GitHub repository, developers can add new tutorials for you to learn for free.

      Start Learning PHP Today

      By learning the basics of PHP, you can jumpstart your career in web development. Since PHP is a vital part of WordPress, this skill can help you create new themes and plugins for personal or public use.

      Here are some ways you can start learning PHP as a beginner:

      1. Watch a YouTube tutorial from creators such as Traversy Media and Envato Tuts+.
      2. Take an online course on Codecademy or Udemy.
      3. Review the PHP manual.
      4. Read a book like PHP Apprentice.
      5. Try an interactive tutorial on W3Schools or learn-php.org.

      If you want to start experimenting with PHP, you may want to create your own website. With our shared hosting plans, you can quickly launch a new site without breaking the bank!

      Web Hosting That Powers Your Purpose

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $1.99/mo.

      shared hosting



      Source link