teleren/devto huggingface dataset:
How to create middleware in Laravel ?
Tags: laravel, webdev, beginners, programming
Published: 2022-06-09 16:42:07

Today we will take a detail look into Laravel Middleware, and will understand the use of it.

## What is Middleware ?

A Middleware is like a bridge between HTTP request and response. it provide a mechanism for inspecting and filtering HTTP requests entering your application.

Let's understand the Middleware by jumping into the code directly. After [Installing Laravel](https://dev.to/shanisingh03/how-to-install-laravel-9-25c4) let's see how we can create and use Middleware.

## How to Create a Middleware ?

For creating a middleware we have to run a command, Let's say for creating a middleware to check year in request named 'CheckYear'.
```php
php artisan make:middleware CheckYear
```

## Add a condition to Middleware

Let's Add a logic to add condition in Middleware to check year.

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckYear
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @param String $year
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $year)
    {
        
        if($request->has('year') && ($request->year == $year)){

            return $next($request);
        }

        return redirect()->route('welcome');
    }
}
```

## Apply Middleware in `routes/web.php`
```php
Route::get('/user/create', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2022']);

Route::get('/user/new', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2023']);
```


You can create any other middleware and use it as per your requirement.

Here you will get complete video tutorial on Youtube.

{% youtube I2N1jAz8nxY %}

If you face any issues while implementing, please comment your query.

Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/techtoolindia)
[Instagram](https://www.instagram.com/techtoolindia/)
[YouTube](https://www.youtube.com/c/TechToolIndia)
Coin Change - VR Mock Coding Interview - #3
Tags: webdev, beginners, programming, tutorial
Published: 2022-06-09 16:40:59

Check out this VR Mock Interview that goes over a “Coin Change” programming interview question. Video linked [here](https://www.youtube.com/watch?v=05lZOCN292I&t=1511s) & verdict/notes below! 

### Verdict

Pass! 

The candidate passed this interview because of their ability to work through the problem, and even though their were hiccups throughout, there wasn't anything that would sink the interview. 
This candidate passed with a 4/5

Ratings

Coding: 3
Communication: 4
Problem Solving: 4
Inspection: 4
Review: 3

What they did well

- Wrote out the input, output and example
- asked intelligent questions
- Thinking Greedy to start, challenges his own thinking and gets to the crux of the problem
- identified the greedy approach, and challenged his assumptions and showed that he couldn't prove it
- Feels like a conversation,
- Very good communicator
- Knew every individual coin was a base case
- Writes great psuedo code
- Great inspection, Good strategy, coding section
- Index selection optimization
- Caught his mistake and added 1 after being prodded

What could be better

- diagram isn’t clear how he is progressing through the problem
- started to fall apart when pushed on the runtime
- Realized the history of the coins didn’t matter after being prodded 
- Got a little lost when he was strategized the coin change solution. Tied up in managing the index
- Didn’t know to reference the call stack when asked about top down vs bottom up
- Kept switching between top down and bottom up without bringing the interviewer along
- Psuedo code , didn’t really have time to code
- No need to do binary search on the coin, a premature optimzation
- First iteration of code wasn’t functional
- Had issues defining the output runtime never asked about the size of the coins
- Didn’t review his code too thoroughly

## Join the Community

Looking for a study partner? [Hackpack](https://www.hackpack.io/) is the most active community. of engineers studying for programming interviews. We hold each other accountable, provide support, and fight burnout to study more efficiently and get the job faster.

You can apply on the site.

[Big Tech Interview Tips Newsletter](https://fangprep.substack.com/)

[Programming Interview Prep Events (Upcoming: Q&A with Senior Meta Engineer)](http://[https://discord.gg/VQkMr234zk?event=970275330294153257](https://discord.gg/VQkMr234zk?event=970275330294153257))
Laravel 9 Middleware - A Complete Guide
Tags: laravel, webdev, beginners, programming
Published: 2022-06-09 16:39:27

Today we will take a detail look into Laravel Middleware, and will understand the use of it.

## What is Middleware ?

A Middleware is like a bridge between HTTP request and response. it provide a mechanism for inspecting and filtering HTTP requests entering your application.

Let's understand the Middleware by jumping into the code directly. After [Installing Laravel](https://dev.to/shanisingh03/how-to-install-laravel-9-25c4) let's see how we can create and use Middleware.

## How to Create a Middleware ?

For creating a middleware we have to run a command, Let's say for creating a middleware to check year in request named 'CheckYear'.
```php
php artisan make:middleware CheckYear
```

## Add a condition to Middleware

Let's Add a logic to add condition in Middleware to check year.

```php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckYear
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @param String $year
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $year)
    {
        
        if($request->has('year') && ($request->year == $year)){

            return $next($request);
        }

        return redirect()->route('welcome');
    }
}
```

## Apply Middleware in `routes/web.php`
```php
Route::get('/user/create', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2022']);

Route::get('/user/new', [App\Http\Controllers\UserController::class, 'createUser'])->middleware(['check-year:2023']);
```


You can create any other middleware and use it as per your requirement.

Here you will get complete video tutorial on Youtube.

{% youtube I2N1jAz8nxY %}

If you face any issues while implementing, please comment your query.

Thank You for Reading

Reach Out To me.
[Twitter](https://twitter.com/shanisingh03)
[Instagram](https://www.instagram.com/shanisingh03/)
[YouTube](https://www.youtube.com/c/TechToolIndia)
Continuous Subarray Sum
Tags: leetcode, dsa, theabbie
Published: 2022-06-09 16:30:45

Given an integer array `nums` and an integer `k`, return `true` _if_ `nums` _has a continuous subarray of size **at least two** whose elements sum up to a multiple of_ `k`_, or_ `false` _otherwise_.

An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.

**Example 1:**

**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.

**Example 2:**

**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.

**Example 3:**

**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false

**Constraints:**

*   `1 <= nums.length <= 105`
*   `0 <= nums[i] <= 109`
*   `0 <= sum(nums[i]) <= 231 - 1`
*   `1 <= k <= 231 - 1`

**SOLUTION:**

    class Solution:
        def checkSubarraySum(self, nums: List[int], k: int) -> bool:
            ctr = 0
            total = [ctr]
            for num in nums:
                ctr += num
                total.append(ctr)
            exists = {}
            for i, f in enumerate(total):
                rem = f % k
                if rem in exists:
                    if i - exists[rem] >= 2:
                        return True
                else:
                    exists[rem] = i
            return False
I made 40+ ready to use templates for any industry
Tags: webdev, programming, html
Published: 2022-06-09 16:38:23

Loopple Landings is a collection of beautiful HTML Responsive Landing Pages & Dashboards templates built on top of Bootstrap and made for any use case. You can simply download a template or duplicate & edit them using Loopple Builder.

Templates Categories:

📚 Education - [check here](https://www.loopple.com/templates/education)
✍🏻 Blogging - [check here](https://www.loopple.com/templates/blogging)
📈 Classifieds Ads - [check here](https://www.loopple.com/templates/classifieds-ads)
👨‍🏫 Coaching - [check here](https://www.loopple.com/templates/coaching)
📁 Corporate Business - [check here](https://www.loopple.com/templates/corporate-business)
🛒 E-commerce - [check here](https://www.loopple.com/templates/ecommerce)
🌾 Farm and Agriculture - [check here](https://www.loopple.com/templates/farm-and-agriculture)
🏥 Hospital - [check here](https://www.loopple.com/templates/hospital)
👨‍⚕️ Medical - [check here](https://www.loopple.com/templates/medical)
📱 Mobile App - [check here](https://www.loopple.com/templates/mobile-app)
🜸 Personal Website - [check here](https://www.loopple.com/templates/personal-website)
🏗 Real Estate - [check here](https://www.loopple.com/templates/real-estate)
🏢 Web Agency - [check here](https://www.loopple.com/templates/web-agency)
📊 Web Elements - [check here](https://www.loopple.com/templates/web-elements)
⚙️ Web Hosting - [check here](https://www.loopple.com/templates/web-hosting)
💒 Wedding - [check here](https://www.loopple.com/templates/wedding)
📦 Dashboard - [check here](https://www.loopple.com/templates/dashboard)

You can see all templates here: https://www.loopple.com/templates

Let me know what you think!
Updates from the 90th TC39 meeting
Tags: javascript
Published: 2022-06-09 16:37:32

There were several items on the agenda, this post focuses on feature proposals and their progress from the meeting that was held between 6-9th June 2022.

###Stage 4:

[Array find from last](https://github.com/tc39/proposal-array-find-from-last): Proposal for `.findLast()` and `.findLastIndex()` methods on array and typed array.

###Stage 3:

[Symbols as WeakMap keys](https://github.com/tc39/proposal-symbols-as-weakmap-keys): Permit Symbols as keys in WeakMaps, entries in WeakSets and WeakRefs, and registered in FinalizationRegistries

###Stage 2:

[String.dedent](https://github.com/tc39/proposal-string-dedent): For multi-backtick templates with automatic margin stripping.

[Duplicate named capture groups](https://github.com/tc39/proposal-duplicate-named-capturing-groups):Allow regex capturing group names to be repeated.

[JSON.parse source text access](https://github.com/tc39/proposal-json-parse-with-source): Extending `JSON.parse` to expose input source text.

###Stage 1:

[Faster Promise adoption](https://github.com/tc39/proposal-faster-promise-adoption): Reduce the number of microtask ticks required to adopt the state of a promise

[RegExp Atomic Operators](https://github.com/rbuckton/proposal-regexp-atomic-operators): Syntax to regular expressions to control backtracking in certain scenarios by treating certain portions of a pattern as "atomic", where backtracking information specific to that portion of the pattern is discarded when it matches successfully.


__More updates:__

`Array#groupBy` is renamed to `Array#group`, but why? [Read on](https://github.com/tc39/proposal-array-grouping#why-group-and-not-groupby)

Tried renaming it on Firefox: 

![group](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jcrhz0sbm6zq8xmty912.png)

<hr />

<center>[@gnumanth](https://twitter.com/gnumanth)</center>
Act — a library for (hierarchical) state machines
Tags: java, statemachine, bdd, eventdriven
Published: 2022-06-09 16:36:00

I created a library for defining executable state machines in your code. This includes the possibility to define hierarchical state machines with sub states. State machines simplify understanding how your code works when you have complex business rules.

As an oversimplified example for learning purposes, look at the following state machine for a shopping cart.

It represents its two fundamental states of being either empty, or non-empty.

The AddItem trigger causes a change to the non-empty cart state.

The RemoveItem trigger causes a change to the empty cart state, if the cart only contains 1 item.

![Image of a statemachine of a shopping cart, with two states](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkeo5ktbeuxosyi8yhv2.png)

And here's how the state machine is presented in code:

``` java
State<Cart, Trigger> emptyCartState = state("Empty Cart", cart -> cart != null && cart.items().size() == 0);
State<Cart, Trigger> nonEmptyCartState = state("Non-Empty Cart", cart -> cart != null && cart.items().size() > 0);

Statemachine<Cart, Trigger> statemachine = Statemachine.builder()
	.states(emptyCartState,nonEmptyCartState)
	.transitions(
		transition(anyState(), nonEmptyCartState, 
			when(AddItem.class, consumeWith(Cart::addItem))),
		
		transition(nonEmptyCartState, nonEmptyCartState, 
			whenInCase(RemoveItem.class, i -> i.state().items().size() > 1, supplyWith(Cart::removeItem))),
		
		transition(nonEmptyCartState, emptyCartState, 
			whenInCase(RemoveItem.class, i -> i.state().items().size() == 1, supplyWith(Cart::removeItem)))
	)
	.flows(
		entryFlow(when(CreateCart.class, init(Cart::createCart)))
	)
	.build();
```

Please visit the [project on GitHub](https://github.com/bertilmuth/act/) for details. I'm looking forward to your feedback.
Newsletter #53
Tags: newsletter
Published: 2022-06-09 16:24:32

Hey, I've been writing weekly for a while, if you'd like to subscribe to my newsletter, it's in spanish but I can start writing in English soon depending on demand:

[ConvertKit Public Page](https://marceloandrader.ck.page/posts)

Last publication:

[🎨 DevTools, Design Systems y más](https://marceloandrader.ck.page/posts/devtools-design-systems-y-mas)
What's your favorite (dev) newsletter?
Tags: discuss, newsletter
Published: 2022-06-09 16:21:40

I really love getting _real_ mail. On paper, in my mailbox. (Although as a grownup 'real' mail is mostly even a bit too 'real'🙄 )

What I don't love so much are e-mails - there are too many, much of the content is too spammy and no, I don't want to buy your magic pills, thank you. 

I want to change that, though - I'm in need of some fun in my inbox, something to look forward to, something to learn. 

That's why I'm looking for your all-time favourite newsletters. Ideally (but not exclusively) with a tech focus. 

I'll go first:

My absolute favourite newsletter is the one by [Stefan Judis] (https://twitter.com/stefanjudis) - in my opinion, it's the perfect mix of new tools, accessibility insights, real-life examples and good music (you can sign up [here](https://www.stefanjudis.com/newsletter/)). 

**What's your favourite newsletter? And why? Any tips appreciated** 🙏
Python Concept Learning Point 2: What is the difference between arguments and parameters?
Published: 2022-06-09 16:13:53

- Parameters are the names appear in the function definition.
- Arguments are the value that actually pass to a function.
- Parameter control what value(parameter) should pass to a function.

```python
def calcaulate_book_cost (number_of_books):
	return number_of_books * 3

print(calcaulate_book_cost(4))
```

In the above example, number_of_books is the parameter, since it appears in the definition of the function.
4 is the argument, since it appear in the function calling and  it is the value actually pass to the function to process.

## Credit
 [Python doc](https://docs.python.org/3/faq/programming.html#faq-argument-vs-parameter) (Accessed at 2022 JUN 09)
Luos Point-To-Point (PTP) connection
Tags: microservices, opensource, tutorial, luos
Published: 2022-06-09 16:10:54

💡 Luos Point-To-Point (PTP) connection allows to find your board's physical position
⏩ https://www.luos.io/docs/luos-technology/node/topology#ptp-network

Luos engine can deal with up to 8 PTP lines on each board to connect as many boards as you want.
Bounded contexts
Tags: architecture
Published: 2022-06-09 16:10:43

## Definition

Summarizing and paraphrasing what was described by [Nick Tune](https://medium.com/nick-tune-tech-strategy-blog/domains-subdomain-problem-solution-space-in-ddd-clearly-defined-e0b49c7b586c):

Domain modeling is about defining a shared language between domain experts and system builders. The same words can have different meanings, depending on context. Domains are boundaries around a set of concepts.

When modelling systems we have to choose the most appropriate domain boundaries with which to align our software and organisational boundaries.

**In domain modeling a bounded context is the boundary of a model that represents the concepts of a domain, their relationships, and their rules.**

Domains are hierarchical. They can be split into subdomains, and each of these "subordinate domains" can be split in turn.

Since a bounded context is a boundary for a model, it could include concepts from multiple subdomains. Or a single subdomain could be modelled as multiple bounded contexts.

As described by [Dave Taubler](https://medium.datadriveninvestor.com/if-youre-building-microservices-you-need-to-understand-what-a-bounded-context-is-30cbe51d5085):

**A bounded contexts is a context — essentially, a system that encapsulates cooperative components — with clearly-defined boundaries that govern what can enter the system, and what can exit it.**

Bounded contexts are as much about organizing teams as they are about software architecture. They enable decoupled code and decoupled teams that can take full ownership over their work.

## Relationship to cohesion and coupling

Bounded contexts are related to the principles of [cohesion and coupling](https://dev.to/fernandoacorreia/cohesion-and-coupling-5632).

When defining multiple bounded contexts within a domain, each bounded context needs to have internal cohesion (i.e. the concepts encompassed by the bounded context should be closely related) and it should be loosely coupled to other bounded contexts (for instance in respect to relationships and business rules).

## References and further reading

- [Domain, Subdomain, Bounded Context, Problem/Solution Space in DDD: Clearly Defined](https://medium.com/nick-tune-tech-strategy-blog/domains-subdomain-problem-solution-space-in-ddd-clearly-defined-e0b49c7b586c)
- [Using domain analysis to model microservices](https://docs.microsoft.com/en-us/azure/architecture/microservices/model/domain-analysis)
- [Domain Language](https://www.domainlanguage.com/ddd/)
- [Discovering the Domain Architecture](https://www.microsoftpressstore.com/articles/article.aspx?p=2248811&seqNum=3)
- [DDD Strategic Patterns: How To Define Bounded Contexts](https://codeburst.io/ddd-strategic-patterns-how-to-define-bounded-contexts-2dc70927976e)
- [Practical DDD: Bounded Contexts + Events => Microservices](https://www.infoq.com/presentations/microservices-ddd-bounded-contexts/)
Flutter based UI task
Published: 2022-06-09 16:03:00

This task was very fun to do. I started by learning the basics and was doing the coding by myself. Then i used the introduction screen package. It was really helpful and i completed the app as suggested in the task. The materials used were as follows:

References: 
- [Flutter Installation](https://flutter.dev/docs/get-started/install)
- [Flutter Docs](https://flutter.dev/docs)
- [Tabs in Flutter](https://flutter.dev/docs/cookbook/design/tabs)
- [Making the dot animated when changing tabs](https://pub.dev/packages/dots_indicator)
- [Introduction Screen Flutter Package](https://pub.dev/packages/introduction_screen)

Resourses:
-Images:
.![page1.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yk1axs2lfor753sod96u.png)

.![page2.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gg5ypnaefc6us1vl7ox.png)

.![page3.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w92ctxhhfrhxkfx271rs.png)

.![page4.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vi46x1kdcmh43odf3o2s.png)

.![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cupfr50yvlae1qu5mvdm.png)
O que podemos aprender corrigindo bugs
Tags: programming, braziliandevs
Published: 2022-06-09 15:58:17

Desenvolver jogos não é uma tarefa simples, um jogo é feito de N sistemas e por mais que tenha um certo cuidado e atenção na hora de criar os códigos sempre terá algo que não saiu como planejado, que não era para acontecer, os famosos bugs. 

A palavra "bug" é utilizada quando ocorre erros no funcionamento de um software ou hardware. São os comportamentos inesperados, na maioria das vezes esses erros são causados por uma falha no código-fonte. 

Dito isso irei trazer alguns pontos que aprendi corrigindo bugs durante esses 6 anos programando jogos. Já trabalhei em 4 empresas de desenvolvimento de jogos, cada uma com segmento diferente, mas todas tinham algo em comum: os bugs. 

No começo eu pegava tarefa de bug sem muito propósito pessoal, meu único objetivo era focar em corrigir. Conforme foi passando o tempo comecei a notar que esse tipo de tarefa gerava um impacto muito grande no meu aprendizado sobre o projeto, ou até mesmo sobre aquele único sistema. 

Corrigir bug é um processo de aprendizagem, pois é preciso fazer depuração no código, conhecer cada parte do sistema na qual esse bug pertence, as vezes o bug está em um trecho específico do sistema C, mas até chegar nesse ponto foi necessário passar pelo sistema A, B e esse caminho rendeu vários conhecimentos.  

Depois que percebi isso, comecei a dar mais importância às tarefas de bugs, sempre que possível pegava bugs com contextos diferentes para corrigir. Claro que só corrigir bugs uma hora acaba ficando chato, por isso é bom ir alternando as tarefas.  

Corrigir bug tem me ajudado a ter um fluxo mais certeiro de pesquisa. Para nós, pessoas programadoras, é comum pesquisar na internet alguma solução para algo que estamos programando e dentro do projeto no qual fazemos parte não é diferente, principalmente se é um projeto que está em andamento há um bom tempo. 

Saber pesquisar é uma habilidade essencial. Durante o fluxo de pesquisa dentro de cada projeto acabei descobrindo o que me fazia chegar mais rápido ao meu objetivo. Cada projeto tem seu padrão, lógicas parecidas em vários sistemas e isso facilita na hora de pesquisar. 

Cada pessoa tem um fluxo de pesquisa, mas na maioria das vezes acaba que alguma coisa é comum e se você quer saber mais sobre como pesquisar de forma eficiente vou deixar o [link para um vídeo no meu canal](https://youtu.be/dJEYFfdGJBs) onde eu abordo mais sobre o assunto. 

Se você chegou até aqui, quero agradecer por ler :heart: e comenta ai o que você aprendeu corrigindo bugs, tenho vários outros pontos mas é assunto para outro artigo. 


Vídeo: [Como pesquisar de forma eficiente](https://youtu.be/dJEYFfdGJBs)