teleren/devto huggingface dataset:
Laravel ORM vs Query Builder vs SQL: SPEED TEST!
Tags: laravel, php, optimization
Published: 2020-11-26 16:01:58

Ever wondered which one of these is faster? 

* ORM
* Query Builder
* SQL

I don't know about you guys but for me this is a BIG question; so I looked into it and I decided to share what I got.

First of all, for small projects and personal blogs it doesn't matter which one you choose, because the database is not that big and either of these three will work just fine.

But what if you're working on an application or a website with a HUGE database?

This is where the answer to this question can be a game changer for you.

So let's find out.

I prepared a database with over 100,000 users and 100,000 articles assigned to each users. (Assigning articles to users was completely random and because of that some users might have 10 articles or have none assigned to them.) 

It's fair to say that it's quite a big database, right? ;)

**WARNING**
I'm pretty sure everybody here already know this but it's worth mentioning that you should NEVER EVER try to get all the records in the database in one query.

If you unknowingly try to do so on a big database you could easily break you application. 

For the purpose of this article I tried to get all 100,000 articles with their users.

Here's what happened: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vwaevriapmjvdmfscwn4.png)

See? It doesn't look good; and here's the code that caused it:

```php
$articles = Article::with('user')
    ->get();
```
The reason for this exception is that the application simply ran out of ram. The database was too big that the ram couldn't handle all the rows of information.

**How to avoid this?**
To avoid this kind of exception you could get the data in smaller chunks. For example we could modify the code above to avoid the exception:

```php
$articles = Article::with('user')
    ->limit(1000)
    ->get();
```
The `limit(1000)` limits the query to take only 1000 records at a time and this will keep a part of ram unused.

Ok; enough with the warning. Let's get to the good stuff.

In this example, I wrote queries that returned the same data using ORM, Query Builder and raw SQL; plus I calculated the time of execution and returned it alongside the fetched information so I can compare which one is faster.

Let's take a look.

**ORM**
```php
$articles = Article::with('user')
    ->limit(1000)
    ->get();
```
> time of execution: 0.07746


**Query Builder**
```php
$articles = DB::table('articles')
    ->join('users', 'articles.user_id', '=', 'users.id')
    ->limit(1000)
    ->get();
```
> time of execution: 0.04171


**SQL**
```php
$articles = DB::select("select * FROM articles JOIN users ON articles.user_id = users.id limit 1000");
```
> time of execution: 0.04461

To be honest I was expecting the raw SQL to be a bit faster than Query Builder but I was wrong. (I tested a couple more times to be sure.)

So there you have it. The winner of this test is Query Builder. 

Of course there's another way to make each of these methods a bit faster, but that's a topic for another post.

Until the next post, take care. 🖤
COVID Tracking Project, Apple's Reduced App Store Commission, Tesla's Security Flaws & more on DevNews!
Tags: news, podcast
Published: 2020-11-26 16:01:28

---
title: COVID Tracking Project, Apple's Reduced App Store Commission, Tesla's Security Flaws & more on DevNews!
published: true
description: Check out S2E5 of the DevNews pod!
tags: news, podcast
series: DevNews Season 2
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/zoxvbu0494gq3sxtjp4v.png
---

### **Another week, another informative and dare I say _newsworthy_ installment of DevNews...** 

{% podcast https://dev.to/devnews/s2-e5-covid-tracking-project-apple-s-reduced-app-store-commission-tesla-security-flaws-and-twitter-fleets %}


### @saronyitbarek and I did what we do best — chat about the top stories software developers don't want to miss:
- Vulnerabilities in the Tesla Model X  
- Twitter's controversial rollout of "Fleet" — an Instagram story-style feature
- What we're thankful for in development/tech (— ok, maybe not newsworthy, but seasonal when it comes to our U.S. listeners!)


### We also spoke with two guests about two other stories:

- [Sarah Maxwell](https://www.linkedin.com/in/sarah-maxwell-9370a4a/?originalSubdomain=uk), spokesperson for the Coalition for App Fairness, about Apple's cuts to developer commission rates for apps
- [Kevin Miller](https://twitter.com/thatkevee), website lead at the COVID Tracking Project, about a resource that has become super important when it comes to getting a clear picture of the pandemic. 

_You can [follow DevNews](dev.to/devnews) to get episode notifications and listen right in your feed_ — or subscribe on your platform of choice! Plus, if you leave us a review, we'll send you a free pack of thank-you stickers. Details [here](https://airtable.com/shr8oKAIMZgdYnBxx). 

## Quick Listening Links
- [Apple Podcasts](https://podcasts.apple.com/us/podcast/s2-e5-covid-tracking-project-apples-reduced-app-store/id1525581923?i=1000500305504)
- [Spotify](https://open.spotify.com/episode/5AVIYxHqYgZpfpMDsH2b3W)
- [Google](https://podcasts.google.com/feed/aHR0cDovL2ZlZWRzLmNvZGVuZXdiaWUub3JnL2Rldm5ld3NfcG9kY2FzdC54bWw/episode/aHR0cHM6Ly9kZXZwb2RzLmRldi9wb2RjYXN0cy9kZXZuZXdzLzEz?sa=X&ved=0CAQQkfYCahcKEwiQrbe6w6DtAhUAAAAAHQAAAAAQAw)
- [Stitcher](https://www.stitcher.com/show/devnews)
- [Listen Notes](https://www.listennotes.com/podcasts/devnews/s2e5-covid-tracking-project-R8h9PJD6yTi/)
- [TuneIn](https://tunein.com/podcasts/Technology-Podcasts/DevNews-p1352512/?topicId=159033240)
- [RSS Feed](http://feeds.codenewbie.org/devnews_podcast.xml)
- [Transcript](https://devpods.herokuapp.com/podcasts/devnews/episodes/68)
- [PocketCasts](https://pca.st/jduaxbw5)

---
_Acknowledgements_ 
- _@levisharpe for producing & mixing the show_
- Our season two sponsors, [Triplebyte](https://triplebyte.com/a/YU8fSn0/d) and [Vonage](https://nexmo.dev/devnews2)!

# 🗞️🗞️🗞️
React Context pattern in Rails
Tags: ruby, rails, react, context
Published: 2020-11-26 15:57:53

---
title: React Context pattern in Rails
published: true
description: 
tags: ruby,rails,react,context
cover_image: https://i.ibb.co/09C2F2d/erda-estremera-sx-Nt9g77-PE0-unsplash-1.jpg
---

I've recently found myself passing a lot of parameters down from controllers to service objects and then to jobs, etc.

This was one of the problems that were solved by the context pattern in React so I tried to do the same in the Rails app that I've been working on.

I had seen something a bit similar to in the [`I18n.with_locale`](https://www.rubydoc.info/gems/activesupport/2.3.17/I18n%2Ewith_locale) function.

So I wrote this:

```ruby
# frozen_string_literal: true

require "concurrent-ruby"

class RequestValueContext
  class << self
    # For the multi threaded environment
    @@request_value = Concurrent::ThreadLocalVar.new

    def with(request_value)
      if get.present?
        raise ContextAlreadyDefinedError,
          "Context already defined!"
      end

      begin
        @@request_value.value = request_value
        yield
      ensure
        @@request_value.value = nil
      end
    end

    def get
      @@request_value.value
    end
  end

  ContextAlreadyDefinedError = Class.new(StandardError)
end
```

And in the `ApplicationController` I've added this:

```ruby
class ApplicationController < ActionController::Base
  around_action :with_context

  def with_context
    RequestValueContext.with("foo") do
      yield
    end
  end
end
```

Then I can access the value using `RequestValueContext.get` from any method that is called "within the controller stack".

A nice feature of this pattern is that the current context can be captured when the using `ActiveJob::Callbacks.before_enqueue` and then provided by `ActiveJob::Callbacks.around_perform` like so:

```ruby
# frozen_string_literal: true

module WithContexts
  extend ActiveSupport::Concern

  REQUEST_VALUE_KEY = "request_value"

  included do
    attr_reader :request_value, :deserialize_called

    before_enqueue :capture_context
    around_perform :provide_context
  end

  def serialize
    super.merge(REQUEST_VALUE_KEY => request_value)
  end

  def deserialize(job_data)
    # "detects" when a job is called by *perform_now*
    @deserialize_called = true

    super

    @doorkeeper_application = request_value
  end

  def capture_context
    @doorkeeper_application = RequestValueContext.get
  end

  def provide_context
    if job_called_by_perform_now?
      # if the job is called by *perform_now* it will be executed inline
      # with the current context
      yield
    else
      RequestValueContext.with_application(request_value) do
        yield
      end
    end
  end

  def job_called_by_perform_now?
    !deserialize_called
  end
end
```

I believe something similar could be done for Proc/Block/Lambda.

I started writing Ruby less than a year ago and I found it to be quite a tricky language so if you have any feedback please let me know.
New Article - Coming Soon! 
Tags: android, kotlin, java
Published: 2020-11-26 15:53:20

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/w0sj1adunlr5fhci7ahj.jpg)
A new article is on the way which is about how you can implement Google Place Autocomplete API using retrofit - Dagger and none other than Google's recommended architectural pattern which is MVVM :)
Object-Oriented Programming
Tags: cpp, java, python, computerscience
Published: 2020-11-26 15:32:39

Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of `objects,` each representing an instance of some `class` and whose classes are all members of a hierarchy of classes united via inheritance relationship.

**Object:** An Object is an identifiable entity with some characteristics and behavior.

**Class:** Class is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a template or a blueprint representing a group of objects that share common properties and relationships.

## Object-Oriented Programming concepts
- Data Abstraction
- Data Encapsulation
- Modularity
- Inheritance
- Polymorphism

![oops](https://dev-to-uploads.s3.amazonaws.com/i/xqnsh7fqaa1mueq9pyle.png)

### Data Abstraction
Abstraction refers to the act of representing essential features without including the background details or explanations.

### Data Encapsulation
Encapsulation is the wrapping up of data and operations/functions into a single unit (`class`).

### Modularity
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

### Inheritance
Inheritance is the capability of one class of things to derive capabilities or properties from another class.

### Polymorphism
Polymorphism is the ability for a message or data to be processed in more than one form.
Download a CSV file from Heroku using Rails console
Published: 2020-11-26 15:25:26

If you need to download some data from Heroku as i did, here is a helpful command to do it.

First, i will create a Ruby file to execute what i need in the Rails console, for example:

```ruby
report = CSV.generate do |csv|
  csv << ["name", "email"]

  users = User.where(
    :created_at => Date.parse("01-11-2020")..Date.parse("30-11-2020")
  )

  users.each do |user|
    csv << [user.name, user.email]
  end
end

STDOUT.puts report

```

In this case, i'm selecting all users created from November 1st until the 30th of November and exporting a csv file with all users names and emails.

In order to run this script in a Heroku Rails console and download this CSV file, we are going to use the Rails runner command.

```sh
cat users.rb | heroku run --no-tty --app=heroku-app-name -- bin/rails runner - > users.csv
```

If you have NewRelic installed in your Rails application on Heroku, probably you will get some limes from it inside your CSV file. To fix that, add this grep option in our command:

```sh
cat users.rb | heroku run --no-tty --app=heroku-app-name -- bin/rails runner - | grep -v "\*\* \[NewRelic\]" > users.csv
```

That's it.
How to upgrade Swagger 2 to OpenAPI 3 in Scala Play project
Tags: scala, playframework, swagger, openapi3
Published: 2020-11-26 15:22:31

Why should I upgrade? Read [this](https://blog.readme.com/an-example-filled-guide-to-swagger-3-2/) blogpost.

Paste your Swagger 2.0 definition [here](https://editor.swagger.io) and select Edit > Convert to OpenAPI 3 from the menu.

Add Authorization with API key as a component.

New Swagger.yml should look something like this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vn2lf3xdlflqex8yuoi0.png)

For generating Swagger UI `"org.webjars" % "swagger-ui" % "3.36.2"` dependency is used (referenced by [iheartradio plugin](https://github.com/iheartradio/play-swagger)).
That way our UI is generated at runtime so we can get rid of swagger-ui-dist (public/swagger) folder.

We need to add `swaggerV3 := true` to `build.sbt`

We need to add this lines to our routes file:
`### NoDocs ###
GET   /docs/swagger-ui/*file      controllers.Assets.at(path:String="/public/lib/swagger-ui", file:String)`

`### NoDocs ###
GET   /assets/*file                 controllers.Assets.versioned(path="/public", file: Asset)`

You will also need to adapt all your current route files to a new style.

After `sbt run`, our new Swagger UI can be accessed on:
http://localhost:9000/docs/swagger-ui/index.html?url=/assets/swagger.json
#DevHack: Create SharePoint library with the Microsoft Graph
Tags: microsoft365, microsoftgraph, api, devhack
Published: 2020-11-27 07:31:06

---
title: #DevHack: Create SharePoint library with the Microsoft Graph
published: true
date: 2020-11-26 15:02:28 UTC
tags: 
- microsoft365
- Microsoftgraph
- API
- DevHack
canonical_url: https://www.eliostruyf.com/devhack-create-sharepoint-library-microsoft-graph/
---

When you are reading this, you are looking to create a SharePoint library from the Microsoft Graph. It is straightforward but a bit confusing because you will have to use the `lists` endpoint. When you are a SharePoint developer, we all learned that a list is not the same as a library, and lists get created under the `/lists/` URL path. Document libraries are not.

> **Info**: [Documentation to create a new list](https://docs.microsoft.com/en-us/graph/api/list-create?view=graph-rest-1.0&tabs=http)

When you want to create a new document library, you can perform the same call as mentioned in the create list documentation page instead of using the `genericList` template value. Use the `documentLibrary` value.


```
POST /sites/{site-id}/lists
Content-Type: application/json

{
  "displayName": "YourLibraryName",
  "list": {
    "template": "documentLibrary"
  }
}
```
  
> **Info**: More information about all properties can be found here: JSON body representation.
  

*That is it for this #DevHack*

![](https://www.eliostruyf.com/devhack-create-sharepoint-library-microsoft-graph/)
"Variables declared with const cannot change" ... well kinda...
Tags: javascript, webdev, node, codenewbie
Published: 2020-11-26 14:55:31

You've heard it 100 times...

**let is mutable
const is immutable (not mutable)**

well... sort of ...

The easy part to clear up is this:
** let is mutable **

If we declare a variable using let, we can re-assign that variable:
``` js
let myName = 'Tyler';
myName = 'John';
```
this works just fine.

Now on to the confusing bit. (ha, no computer science pun intended.)

Basic types with const are immutable.
Examples of this:
``` js
const myName = 'Tyler';
myName = 'John'; // this line will throw an error

const myNumber = 7;
myNumber = 3; // this line will throw an error
```
We cannot re-assign a string or number declared with const.

**... "BuT WhaT AbOuT ObJectS AnD ArRaYS???" ...**

good point. Check this out:
``` js
const employee = {
    id: 12345,
    name: 'John Doe',
    address: {
        street: '123 Circle St.',
        city: 'Pittsburgh',
        zip: 11111,
    }
}

employee.id = 99999,
employee.address = {}

console.log(employee) // { id: 99999, address: {} }
```

We used const, but we can still change the inside values of the object itself. We even deleted a key/value pair entirely!

The same happens with Arrays:
``` js
const employee = [99999, 'John Doe', ['Cleveland', '123 Circle Street', 11111]]

employee.pop()
employee.pop()

console.log(employee) // [ 99999 ]
```

Again, we used const, but we could still manipulate the inside values of the array.

This being said, we cannot re-assign the entire employee object or array, the following examples will result in an error:
``` js
const employee = [99999, 'John Doe', ['Cleveland', '123 Circle Street', 11111]]

employee = [4444, 'Jane Doe']

console.log(employee) // Error, cannot re-assign const


// example 2
const employee = {
    id: 12345,
    name: 'John Doe',
    address: {
        street: '123 Circle St.',
        city: 'Pittsburgh',
        zip: 11111,
    }
}

employee = {}

console.log(employee) // Error, cannot re-assign const
```

So we have learned that we can change the insides of an object and array even though it was declared with const.

**How do we stop this from happening?**

One solution is to use Object.freeze().
This will work for objects and arrays that are not nested.

If an object or array is nested, the nested elements will still be able to be changed.

To "deep freeze" an object or array, we would need to create our own deep freeze function or use an external library.

Thanks for reading, for more tech content you can find me here:
**Youtube => https://www.youtube.com/austinbeaufort**
**Twitter => https://twitter.com/AustinBeaufort**
What are the most generous free plans you know?
Tags: webdev, watercooler
Published: 2020-11-26 14:54:27

---
title: What are the most generous free plans you know?
published: true
description: 
tags: webdev, watercooler
cover_image: https://www.productfocus.com/wp/wp-content/uploads/2019/10/Free-Image.jpg
---
Could you share some services with the most generous free plans across various categories like cloud storage, hosting platforms, database services, CI/CD tools, productivity and collaboration apps, etc?

Some of my favs include [Degoo](https://degoo.com/) with 100GB free cloud storage, [Netlify](https://netlify.com/) with unlimited projects and 100GB bandwidth, and [DynamoDB](https://aws.amazon.com/dynamodb/) with 25 GB of data storage.
How will I identify resource default url in laravel?

Tags: laravel, php
Published: 2020-11-26 14:50:39

I am running this command for model, migration, resource controller.

`php artisan make:model QuestionAnswer -mc -r ..`
My Edit Function

`public function edit(QuestionAnswer $questionAnswer)
    {
        // return $questionAnswer;
        return view('backend.faq.edit',get_defined_vars());
    }`
Route one in web.php : `Route::resource('faq','QuestionAnswerController'); in view : {{route('admin.faq.edit',$questionAnswer->id)}}`

Route two in web.php : `Route::resource('question-answer','QuestionAnswerController');` in view `{{route('admin.question-answer.edit',$questionAnswer->id)}}`

in Edit function for Route one : `$questionAnswer` object return null. but for Route two : `$questionAnswer` return object mean expected output ..

Follow this question

Question is there possible way to find out what exact url I will write ? .. like question-answer.. or command line ...or how will I figure it out ? I think there must be something..



How will I know I need to write question-answer this ? by default it works... when i write faq i need to change in edit function variable($faq) .

How will I know by default url (`question-answer`) will work ..when `php artisan route:list` command give us all route list.. and when I make model `Category` laravel create table name categories and follow grammar rules
React not easy to learn?
Tags: react, javascript
Published: 2020-10-25 17:42:30

---
title: React not easy to learn?
published: true
description: 
tags: React, javascript
//cover_image: https://direct_url_to_image.jpg
---

I am a complete newbie to React however as someone who knows some Vue I am currently attempting to rebuild a Vue app and it'#s not going that well. Everyone seems to suggest React is just JS and JSX it's easy to learn. Is it?  It just seems so alien to me I thought having dabbled a bit with Gatsby I know the basics of using JSX and I know some ES6 stuff I can learn React... it's turning out to be much more difficult than I thought. 

For a start I don't like the docs (imo Vue docs are much better) I don't find them helpful for example I was trying to render an array of objects which apparently is not allowed in React (why?) all the example in the docs shows is a basic array of numbers? In the end I found an answer on SO so in the end did this: 

```javascript
let methodsList = arrayMethods.map((method) => 
<li className="list-group-item"
 key={method.name}>
<strong>{method.name}</strong> {method.method}</li>)

...
<ul className="list-group bg-danger">
  {methodsList}
</ul>
```

Perhaps I am approaching it wrong I don't know but I am confused and struggling to grasp bits of it does anyone have any resources that go over the key concepts?
Laravel Password Validation: Password should contain letters and numbers only  
Tags: laravel, php, oop
Published: 2020-11-26 14:09:38

So today i was assigned a somewhat simple yet complicated task. At first  i was  like, "oh! so you just need me to validate your password to accept only letters and numbers? " Easy, I thought. So i embarked to the usual programmer's  way of hunting for answers.  
The closest solution to my problem was this 
{% https://laravel.io/forum/04-05-2017-validation-alphabet-and-numeric-value %}
 But see, the problem with that solution is  if you input a password of numbers only or alphabets alone, the validation will still pass.

 Second  closes solution was on stackoverflow: {% https://stackoverflow.com/questions/31539727/laravel-password-validation-rule %}
  so  I had to reformat the  regex from 
** regex: /^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/| **

          to this
** regex:/^.*(?=.{2,})(?=.*[a-zA-Z])(?=.*[0-9]).*$/' **

That took care of the problem except i could still input my letters and numeric characters plus the special characters and the validation still passes.
**So problem not solved yet!!!!**
**THE TRICK**
Laravel documentation says this on  alpha_num:
alpha_num

The field under validation must be entirely alpha-numeric characters.
 {% https://laravel.com/docs/5.4/validation#rule-alpha-num %}
 so i had to get a lil bit creative in order to get rid of the special characters by adding the alpha_num validation rule and it worked.
I was able to input letters and Numbers as password.
 here is my final code
**
'password'              => ['required',  'min:8','alpha_num', 'regex:/^.*(?=.{2,})(?=.*[a-zA-Z])(?=.*[0-9]).*$/'],

'confirm-password'      =>  ['required','min:8', 'alpha_num','same:password','regex:/^.*(?=.{2,})(?=.*[a-zA-Z])(?=.*[0-9]).*$/'], 
**
 I hope it helps someone!
Yo, I'm going to become a Software Dev
Published: 2020-11-26 14:02:15

Hey there!

I'd like to learn to code. I don't have any special talent, but I have a strong desire to change my life.

I see that a lot of people start with HTML/CSS, but some tell me that I should first start with the Fundamentals of Computer Science. Which path is the right one to take?

I don't have any illusions about "learn everything in 30 days or less", but in a year I want to be hired as a Software Dev. What would you say, is that real?