Laravel Cheat Sheet for Eloquent ORM

ORM (Object-relational mapping) is used to make database CRUD operations easier. Laravel comes with Eloquent ORM. This tutorial is created to provide some of the frequently used cheat sheet for Laravel Eloquent ORM

  1. Ordering Eloquent hasMany() relationship

Add ->orderBy() to the hasMany relationship to get ordered output of a specified column.

return $this->hasMany('Detail::class')->orderBy('column');
Code language: PHP (php)
  1. Eloquent’s where() method

Here are some useful cheat sheet for eloquent’s where() method.

$detail = Detail::where("id","!=",50)->get(); // Any of the following may be used as the second parameter (and use the third param for the value) // =, <, >, <=, >=, <>, !=, LIKE, NOT LIKE, BETWEEN, ILIKE $detail = Detail::where(function ($query) { $query->where('a', '=', 1) ->orWhere('b', '=', 1); })->get(); $detail = Detail::whereRaw('age > ? and votes = 100', array(25))->get(); $detail = Detail::whereRaw(DB::raw("id in (select detail_id from students GROUP BY students.detail_id)"))->get(); $detail = Detail::whereExists(function($query){ $query->select(DB::raw(1)) ->from('students') ->whereRaw('students.detail_id =') ->groupBy('students.detail_id') ->havingRaw("COUNT(*) > 0"); })->get(); // Any of the following may be used instead of Detail::whereExists // ->orWhereExists(), ->whereNotExists(), ->orWhereNotExists() $detail = Detail::whereIn('column',[1,2,3])->get(); // Any of the following may be used instead of Detail::whereExists // ->orWhereIn(), $detail = Detail::whereNotIn('id', function($query){ $query->select('student_id') ->from('students') ->groupBy('students.student_id'); })->get(); // Any of the following may be used instead of Detail::whereExists // ->whereNotIn(), ->orWhereNotIn
Code language: PHP (php)

Here are some more useful cheat sheet for NULL or NOT NULL in laravel eloquent.

->whereNull('column') ->orWhereNull('column') ->whereNotNull('column') ->orWhereNotNull('column')
Code language: PHP (php)

Cheat sheet to filter by Day, Month, Year, Date options.

->whereDay() ->whereMonth('column', '=', 1) ->whereYear('column', '>', 2019) ->whereDate('column', '>', '2019-05-05')
Code language: PHP (php)
  1. Prevent Eloquent from adding created_at or updated_at timestamps

Disable both created_at and updated_at in the model to disable the timestamps

const UPDATED_AT = null; const CREATED_AT = null;
Code language: JavaScript (javascript)

Make sure to remove this from the migration

Code language: PHP (php)
  1. restore() soft deleted Eloquent

Use the restore() method to undelete a record.

Code language: PHP (php)

Make sure to add following lines in the model to enable SoftDeletes.

use SoftDeletes;
Code language: PHP (php)
  1. Joins in Eloquent

Here are some useful cheat sheet for eloquent’s join() method.

$product = Product:where('id', $productId) ->join('businesses','product.business_id','=','') ->select('','')->first(); $product = Product:where('id', $productId) ->leftJoin('businesses','product.business_id', '=', '') ->select('','')->first(); $product = Product:where('id', $productId) ->join('businesses',function($join) use($cats) { $join->on('product.business_id', '=', '') ->on('', '=', $cats, 'and', true);})->first();
Code language: PHP (php)
  1. Find an item by Primary Key in Eloquent, or throw a ModelNotFoundException

findOrFail($id) method will find a model by it’s primary key or throw an exception if it’s not available.

$id = 10001; $user = User::findOrFail($id);
Code language: PHP (php)
  1. Cache in Eloquent

You can retrieve an item from the cache without loading it all the item.

$details = Cache::remember('details', $seconds, function () { return DB::table('details')->get(); });
Code language: PHP (php)

rememberForever method is used to retrieve an item from the cache or store it forever

$details = Cache::rememberForever('details', function () { return DB::table('details')->get(); });
Code language: PHP (php)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.


Getting Started with Django

Django is an open-source, high-level and free Web framework created using Python. It follows the Model View Template(MVT) architectural pattern. In this tutorial you’ll learn to setup a Django 2.2 project from scratch.

Why Django?

Django is one of the best framework available today. It acts as a quick solution for web development and delivers high-quality code with better security. Django takes it very seriously and helps to avoid SQL injection, cross-site scripting etc. Let’s look at some of the core features in Django

  1. Faster : It’s considered to be one of the fastest framework built by python language.It encourages rapid development with a clean and pragmatic design.
  2. More Packages : Django comes with many components that helps to develop faster and easier.No need of downloading any components separately as Django installs all the extras, packages and the related dependencies.
  3. Versatile : Django is used to develop all sorts of applications – from basic development to complex development. Therefore, Django is extremely versatile in all fields.
  4. Secure : Django is as secure as any web framework can be. It provides tools to prevent common mistakes causing security problems.
Installing Django


Make sure you have installed Python in your PC. Click onΒ Install PythonΒ If you haven’t installed Python on your PC/ Mac.

Type the following command at your terminal to install Django on your PC/ Mac

pip install Django==2.2
Starting a new Django application

Now that we have completed the basic setup, to start Django application. Let’s start the Project.

django-admin startproject sampleProject

After initiating the project. Type the following command to get into the project directory

cd sampleProject

After creating the project, you will find a list of files inside the project directory as below.

|-- sampleProject | |-- | |-- sampleProject | | | | | | | | | | | |
  1. : Init just tells the python that this is to be treated like a python package.
  2. : Manages all the settings of your project.
  3. : The main controller which maps it to the website.
  4. : Serves as an entry point for WSGI compatible web servers.
|-- sampleProject | |-- | |-- sampleProject | |-- app | | |--migrations | | | | | | | | | | | | | | | | | | | | | |

Type the following command at your terminal to create the list of files inside the app as shown above.

python startapp app
Code language: CSS (css)

Now add the following code to the file which will return a httpResponse


from django.http import HttpResponse def index(request): return HttpResponse("<h1 st
Code language: JavaScript (javascript)

To map the view with the URL, add the following code in


from django.contrib import admin from django.urls import path from app.views import index urlpatterns = [ path('admin/',, path('',index), ]
Code language: JavaScript (javascript)

Now It’s time to run the application, To start the server simply type the command show below at your terminal.

python runserver
Code language: CSS (css)

Feel free to drop your thoughts at the comment section!

React Native

React Native Vs Flutter : Comparison

React Native and Flutter has become one of the most trending technologies for Mobile Application Development in 2019. Both the technologies are built by leading tech giants. Flutter is backed by google and React Native by Facebook.

Due to the increasing usage of mobile applications. app development is becoming a buzz. Almost every tech company need to have mobile app development team to remain competitive among other tech companies. iOS and Android has given native tools. Such as Xcode and Swift for iOS, Android Studio and Kotlin for Android to develop applications for their platform.

However, this requires the developers to learn separate languages to each specific platform and it’s time consuming to develop both applications separately. As a result, tech companies have moved from native development to Cross- Platform development to build apps for both iOS and Android quicker with less time using single code base.


Flutter is Google’s mobile SDK for develop high quality applications on iOS and Android. It’s a reactive, Open Source development framework. Flutter is the primary method to create applications for Google Fuchsia.

Programming Language – Dart Flutter uses Dart programming language to build cross-platform applications. Dart is not a popular programming language among the developers but it’s very easy to understand for Java developers as it supports most of the object-oriented concepts. Here’s the documentation for Dart.

Architecture Flux and Redux are the two main patterns used in React native applications. Both Flux and Redux have actions. Actions can be compared to events. In Flux, an action is a simple JavaScript object, and that’s the default case in Redux too.These frameworks are about unidirectional data flow and storing your application’s state in one central place called Store, and make your app components as stateless as possible.

Community Support Flutter gained a lot of attention when Google promoted it in 2017. The Flutter community is growing rapidly so far, meetups and conferences are taking place online. yet, there are still not enough resources for developers to solve common issues.

React Native

React Native is an open-source mobile application framework created by Facebook to develop application for for Android, iOS and UWP (Universal Windows Platform).It’s a JavaScript framework for writing real, natively rendering mobile applications.

Programming Language – JavaScript React Native uses JavaScript to build cross-platform applications. Javascript is widely used by many web developers.It is commonly used with React and other popular JavaScript frameworks. Javascript is very easy to master, which helps react native developers to develop mobile application with a little bit of training. With this in mind, companies adopted React Native as a no-brainer.

Architecture Flutter uses BLOC pattern. Its a state management system for Flutter recommended by Google developers. It helps in managing state and make access of data from a central place in your project.

Community Support React Native launched in 2015 and has gained in popularity ever since. There is a active community of React Native developers on GitHub and lots of meetups and conferences around the world.

Flutter vs. React Native: Differences

Let’s look at some of the key differences and similarities between react native and flutter in a nutshell.

Founded / Created ByGoogleFacebook
Programming LanguageDartJavascript
Native PerformanceFasterGood
Learning CurveQuite steep, you need to learn Dart.Easy to pick up, especially if you used Javascript before
Live ReloadSupportedSupported
Initial ReleaseMay 2017Jan 2015
Github Repoflutter/flutterfacebook/react-native
React Native

Getting Started with React Native 0.59

React Native is an open-source , cross platform mobile application framework created by Facebook. It is used to publish Apps for Android, iOS and UWP. This tutorial focuses on how to install react native on windows.

The react-native documentation is the best place to get started. but I’ll be giving you a quick starter guide with easier steps and more detail.

Before installing react native. Make sure to install these on your PC

  1. Node.js : npm is the package manager for the Node JavaScript platform. It is used to install node programs.
  2. Java Runtime Environment : The Java Runtime Environment (JRE) is a combination of tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries.
  3. Android Development Environment : Android SDK(Software Development Kit) that enables developers to create applications for the Android platform.

Install react-native-cli by heading over to your terminal and type the following command

npm install -g react-native-cli

Starting a new application

Now that we have completed all the basic setup to start react native application. Let’s initiate the Project.

react-native init ReactNativeProject

After initiating the project. Type the following command to get into the project directory

cd ReactNativeProject

Finally, You are ready to run your project in both android and iOS (A Mac PC is required to build projects with native code for iOS).

Type the following command in your terminal to run for iOS
react-native run-ios
Type the following command in your terminal to run for Android
react-native run-android

The build process may vary every time you run the project.The launch packager will show the process status of the build.If the build fails, It wil indicate the errors.

Feel free to drop your thoughts at the comment section!


Android Q : What’s New ?

Android Q Beta 1 is the new update for android platform. There are some amazing features hidden in the developer options or even deeper in the new update. Let’s take a look into some features in detail.

Android Q Update Timeline
Image Source : Google

Google has divided its beta release into six releases. We currenly have the March beta 1 release. Take a look at the Android Q Beta program overview. Android Q beta is currently supported to all Pixel devices (Pixel, Pixel XL, Pixel 2, Pixel 2 XL, Pixel 3, Pixel 3 XL).

The beta 1 looks fine and everything works well, and there are some minor bugs and design flows, though, hope that the issues will be sorted before the release. Let’s find out the new features in Android Q, that google has made so far,

  1. Quicker App Launch Time

With the introduction of Android Q Beta opening apps has become a lot quicker and easier than the previous android versions.

Image Source : Google
  1. Privacy Protection

Android has released frequent Security updates in the past to improve the users’ privacy and security and it has continued to the newest Q beta.

Image Source : Google

Some of these advanced features include file-based encryption, locking down camera/mic background access, encrypted backups, lockdown mode, Google Play Protect, OS controls requiring apps to ask for permission prior to accessing the sensitive resources, etc. Android Q beta has included more control over different apps and their access to shared files.This is considered to be one of the biggest updates and enhancements to Android Q.

  1. Dark Mode

Google has slowly added dark modes to their own apps over the past and finally it is now available for Android Q Beta.

There are many ways to enable dark mode to your pixel device. The easiest way to turn on dark mode is to simply turn on Battery Saver mode. This will instantly change all of your menus to dark theme.

  1. Screen recording

Many third party Android applications has offered the screen recording feature but being able to record your screen without an app is amazing, however, Android Q Beta has listed the feature under developer option.

Open Settings menu and click on the Developer Options. From there, you’ll find a flag titled “settings screenrecord long press.” Toggle that on, you’re ready to record your screen.

  1. Sharing Shortcuts

Sharing is now made easy with more cleaner and easier to share content out of one app and into another.In fact, Google is in the process of expanding the Shortcut info API for streamlining the process of integration. The API will also enlist the pre-Android Q devices for using their functionalities in the Direct Share. You can get an early sample app source code.

The first beta of Android Q brings some smaller changes and fixes that are missed over the previous android versions. If you liked the article, feel free to share your opinion in the comment section below.


Convert PHP Array To JSON : Examples

This tutorial focuses on converting PHP Array to JSON. It is used to read data from the server and display it to the Web. JSON is a text format , and We can convert any JS Object into a JSON format.

  1. Covert PHP array to JSON

PHP is capable of handling JSON and it has some built-in functions to handle them. json_encode() is used to convert objects, arrays in PHP to JSON format. The PHP json_encode() function returns the string containing a JSON equivalent of the value passed.

The syntax of json_encode() function as following.

json_encode(value, options)

Here’s how we need to convert the numerically indexed array into JSON

<?php $names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer']; $namesJSON = json_encode($names); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :["Bishrul","Bishrul Haq","Developer","Software Engineer"]
Code language: JavaScript (javascript)

If you want the array to be output as Object , you can use JSON_FORCE_OBJECT option as below,

<?php $names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer']; $namesJSON = json_encode($names,JSON_FORCE_OBJECT); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :{"0":"Bishrul","1":"Bishrul Haq","2":"Developer","3":"Software Engineer"}
Code language: JavaScript (javascript)
  1. Convert PHP Associative Array to JSON

To Convert a key-value pair array (Associative Array), you can also use json_encode() to convert objects, arrays in PHP to JSON format.

Here’s how we need to convert an associative array into JSON

<?php $names = ['Name'=>'Bishrul', 'Full Name'=>'Bishrul Haq', 'Details'=>'Developer', 'Designation'=>'Software Engineer']; $namesJSON = json_encode($names); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :{"Name":"Bishrul","Full Name":"Bishrul Haq","Details":"Developer","Designation":"Software Engineer"}
Code language: JavaScript (javascript)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.