<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Demian Kostelny on Medium]]></title>
        <description><![CDATA[Stories by Demian Kostelny on Medium]]></description>
        <link>https://medium.com/@demian.kostelny?source=rss-152f864614c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k0hoMybH3d1w-MvTljkZOA.jpeg</url>
            <title>Stories by Demian Kostelny on Medium</title>
            <link>https://medium.com/@demian.kostelny?source=rss-152f864614c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:10:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@demian.kostelny/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Self-hosted CI/CD deployments with Forgejo Runner]]></title>
            <link>https://blog.stackademic.com/self-hosted-ci-cd-deployments-with-forgejo-runner-ba03104127be?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba03104127be</guid>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 20:31:01 GMT</pubDate>
            <atom:updated>2026-08-21T20:31:01.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGVkzwf03kZVj_b7GUhNWw.png" /></figure><p>Have you ever heard that you can easily set up a fully self-hosted CI/CD pipeline with a fully customized personal git instance? If your answer is no and you’re interested in learning how to set it up quickly, then this article is for you. And of course, if you’re a person who cares about privacy, this tutorial could help you expand your toolkit for Git.</p><p>As always, we will begin by learning all the basics about Forgejo and the base features that are provided by this open-source self-hosted Git instance (or even better, call it a GitHub analog).</p><h3>Introduction: What is Forgejo and how to set up your instance fast?</h3><p>Previously, I already published a starter guide on how you can quickly set up a self-hosted Forgejo instance with privacy-friendly settings. In this guide, we are going to follow the same steps, but it will be more expanded, as we will run more containers to support self-hosted CI/CD pipelines.</p><p>But first, let me answer the fundamental question: what is Forgejo? Briefly, Forgejo is a fully self-hosted Git application like Bitbucket, GitLab, or GitHub. The difference is that you control all the data and you can do whatever you want. A lot of teams use solutions like that for their internal Git system to protect code from breaches, AI, or just for privacy concerns.</p><h3>Fast setup with Docker</h3><p>Of course, you can set up Forgejo without Docker or Podman, but it will be much harder than using a solution with containers. We are going to begin by creating a new Docker Compose file (also don’t forget to create a separate folder for your instance):</p><pre>version: &quot;3.8&quot;<br><br>networks:<br>  forgejo:<br>    external: false<br><br>services:<br>  db:<br>    image: postgres:16-alpine<br>    container_name: forgejo_db<br>    environment:<br>      POSTGRES_DB: ${POSTGRES_DB}<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>    volumes:<br>      - ./postgres:/var/lib/postgresql/data<br>    networks:<br>      - forgejo<br>  forgejo:<br>    image: codeberg.org/forgejo/forgejo:16<br>    container_name: forgejo<br>    environment:<br>      - USER_UID=1000<br>      - USER_GID=1000<br>      - FORGEJO__database__DB_TYPE=postgres<br>      - FORGEJO__database__HOST=db:5432<br>      - FORGEJO__database__NAME=${POSTGRES_DB}<br>      - FORGEJO__database__USER=${POSTGRES_USER}<br>      - FORGEJO__database__PASSWD=${POSTGRES_PASSWORD}<br>      - FORGEJO__actions__ENABLED=true # this is important to enable CI/CD<br>    volumes:<br>      - ./forgejo:/data<br>      - /etc/localtime:/etc/localtime:ro<br>    ports:<br>      - &quot;3000:3000&quot;<br>      - &quot;2222:22&quot;<br>    depends_on:<br>      - db<br>    networks:<br>      - forgejo<br>  # And yes, we are going to run docker-in-docker (what a surprise!)<br>  docker-in-docker:<br>    image: docker:dind<br>    container_name: forgejo_dind<br>    privileged: true<br>    restart: unless-stopped<br>    command: [&quot;dockerd&quot;, &quot;-H&quot;, &quot;tcp://0.0.0.0:2375&quot;, &quot;--tls=false&quot;]<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;docker&quot;, &quot;-H&quot;, &quot;tcp://127.0.0.1:2375&quot;, &quot;info&quot;]<br>      interval: 2s<br>      timeout: 5s<br>      retries: 15<br>    networks:<br>      - forgejo<br>  runner:<br>    image: data.forgejo.org/forgejo/runner:13<br>    container_name: forgejo_runner<br>    restart: unless-stopped<br>    depends_on:<br>      docker-in-docker:<br>        condition: service_healthy<br>      forgejo:<br>        condition: service_started<br>    environment:<br>      DOCKER_HOST: tcp://docker-in-docker:2375<br>    user: &quot;1001:1001&quot;<br>    volumes:<br>      - ./runner-data:/data<br>    networks:<br>      - forgejo<br>    command: forgejo-runner daemon --config /data/runner-config.yml<br>volumes:<br>  forgejo_db_data:_db_data:</pre><p>I know what you’re thinking after you saw that there will be a Docker-in-Docker container, and you already are calling DevOps police, but let me explain this part briefly. Forgejo runner (container that will run CI/CD) can’t run Docker commands inside its own container for the workflows, and to solve this problem, there are two possible solutions.</p><p>First solution: we can create a new Docker instance inside Docker so it can be used by the Forgejo runner as we just did.</p><p>Second solution: nest a host’s UNIX socket and use it to run Docker commands.</p><p>For our case, it will be easier and better to use the docker-in-docker solution, as we are already running a Forgejo instance with Docker.</p><h3>Installation and configuring all configs</h3><p>After the docker-compose.yaml is created, the next step will be to create a .env file in the same folder where docker compose and paste the following variables:</p><pre>POSTGRES_DB=forgejo_db<br>POSTGRES_USER=forgejo_db<br>POSTGRES_PASSWORD=forgejo_pass_123</pre><p>Don’t forget to generate a strong password in case you’re going to host this in your homelab or VPS server. Don’t run all containers at once; first, you need to start only the database and forgejo containers:</p><pre>$ docker compose up -d db forgejo</pre><p>If there are no errors in the container logs, then you can continue and move into the installation step. Open <a href="https://localhost:3000/">https://localhost:3000</a>, and you should see the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*dOdBmpnWoyhSRaOZ.png" /></figure><p>All installations can be easily completed via this page if you don’t want to do configuration via a configuration file. Also, you can fill in additional settings if you need, for example, an SMTP server for your git instance. If no need that, then scroll down and open the “Administrator account settings”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*XHkY1aEP9wWO4Gw9.png" /></figure><p>Just fill in your administrator account credentials and save them, and after that, just click on “Install Forgejo” to start the installation process. It can take a few seconds; after that, you should see the dashboard page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LuK8bO-o0jCm7alz.png" /></figure><p>Great, now get back into your terminal and run the following command to create a Forgejo runner config:</p><pre>$ mkdir -p runner-data/.cache<br>$ docker run --rm data.forgejo.org/forgejo/runner:13 \<br>  forgejo-runner generate-config &gt; runner-data/runner-config.yml</pre><p>Okay, now you’ll need to open again Forgejo UI and register the runner — click on the avatar in the top right corner -&gt; Site administration -&gt; Actions -&gt; Runners -&gt; Create new runner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*g1wkfcDqavVkmvXG.png" /></figure><p>Just type the runner name and create. Copy the UUID and token — you will need this for runner configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*0OKsx0VML-l4vBzU.png" /></figure><p>Open your editor and open the following file: runner-data/runner-config.yml, and find the “server” variable and just paste the runner configuration inside the “connections” variable:</p><pre>container:<br>  network: &quot;host&quot; # edit this variable too</pre><pre>server:<br>  connections:<br>      forgejo:<br>        url: <a href="http://forgejo:3000/">http://forgejo:3000/</a> # Important, type here forgejo, not localhost<br>        uuid: cfb0f9aa-afff-40d3-aad2-077e9db72584<br>        token: edccd714edb2c15ca43edf6e851f64cee0c495d7</pre><p>It’s time to start all containers; just run the following command:</p><pre>$ docker compose up -d<br>$ docker compose logs -f runner # run this to check logs of forgejo runner container\</pre><p>If everything is okay, you should see the following message inside the Forgejo runner container:</p><pre>time=&quot;2026-08-20T06:13:51Z&quot; level=info msg=&quot;[poller] launched&quot;</pre><h3>Creating the first workflow</h3><p>We are going to create a pretty simple deployment workflow just to see that it will be triggered after we push some changes into repositories that we host inside our Forgejo instance. But before you run your first deployment, we need to have something we can deploy, and first we need a new repository.</p><p>Just open the dashboard and click on the plus button and “New repository”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*N8wLXhtpc6ib-H80.png" /></figure><p>Like on GitHub, you type all the information and settings here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*VFqqv-Cqqmy8fdXe.png" /></figure><p>And after that, just follow the steps to clone the repository into your local machine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*fhMlFfmLljyfcaZN.png" /></figure><p>After the repository is cloned, open it in the IDE and create the following folders and file with the workflow .forgejo/workflows/demo.yml:</p><pre>on: [push]<br>jobs:<br>  test:<br>    runs-on: docker<br>    steps:<br>      - uses: https://code.forgejo.org/actions/checkout@v4<br>      - run: echo &quot;Forgejo + Actions is alive&quot;</pre><p>In short, this workflow will be triggered only when we push new changes into the repository, and it will just log a “Forgejo + Actions is alive” message in the action logs. And don’t forget to commit your changes:</p><pre>$ git add .<br>$ git commit -m &quot;first commit&quot;<br>$ git remote add origin http://localhost:3000/runneruser/myrepo.git # don&#39;t forget to type your repo URL here<br>$ git push -u origin main</pre><p>It will ask for credentials from your Forgejo account; just type your admin account credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*TBwtXwUw-t2BPu9g.png" /></figure><p>Go back to the repository page and open the “Actions” tab; you should see that the action was triggered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*yrXJ3c-wANW25kxr.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*Zis2tuos5dCXbAAA.png" /></figure><p>You can also check progress logs for each step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*Ux4qGxjEnX70VYPj.png" /></figure><p>And if everything went well, you will see green checkmarks in all steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*t62J42PitT-c7Xz2.png" /></figure><p>Congratulations! You just created your first workflow and fully self-hosted CI/CD with custom deployments; now it’s time to discuss what we should do next and other capabilities in Forgejo.</p><h3>What’s next?</h3><p>So now you got full understanding of how you can do this, and the next question is — what should I do next? Just like on GitHub, you can use similar <a href="https://docs.github.com/en/actions/concepts/workflows-and-actions/workflows">workflow schemas</a> to create your deployment workflows that will be executed via the Forgejo runner and a Docker-in-Docker container. If you don’t have any experience with this topic, I really recommend trying to set up a custom CI/CD deployment for a simple Node.js application inside an EC2 instance.</p><p>More about Forgejo, workflows, CI/CD, and self-hosting, I’m going to explain and show in the next article series — for now, thank you for reading this guide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba03104127be" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/self-hosted-ci-cd-deployments-with-forgejo-runner-ba03104127be">Self-hosted CI/CD deployments with Forgejo Runner</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forgejo — or a full guide on how to create a self hosted git instance]]></title>
            <link>https://blog.stackademic.com/forgejo-or-a-full-guide-on-how-to-create-a-self-hosted-git-instance-02a39d688630?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/02a39d688630</guid>
            <category><![CDATA[forgejo]]></category>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 09:01:02 GMT</pubDate>
            <atom:updated>2026-06-29T12:53:39.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn_mnemECZlQrZMk5f9TJw.png" /></figure><p>With the recent anti-privacy and anti-freedom of speech laws pushed in around the world (for example, the Online “Safety” Act or, to be more accurate, the Backdoor Act in the UK), it is great to gain back all control for your data and devices, with no exceptions for your workspace or your personal life.</p><p>In this full guide, I’m going to show you how to properly set up a self-hosted Git server in your homelab where you control everything, and you are the only person who decides what to do with the data that you own.</p><h4><strong>What is Forgejo?</strong></h4><p>In short, just imagine it like a small version of GitHub — but it can be fully self-hosted on your local machine or virtual server, and basically, you’re the owner. This is a good solution for teams that really value privacy in development projects.</p><p>The easiest way to install Forgejo is just by running a Docker container, and yeah, that’s all you need for this guide — just a local machine with Docker Engine. But you can also install from binaries. In my case, I’m going to install everything via Docker, because it’s much easier for everyone who will read this article.</p><h4>Easy installation and configuration</h4><p>Forgejo is fully <a href="https://codeberg.org/forgejo/forgejo">open source</a> — here is an example below of my Docker Compose file with all configuration set:</p><pre>services:<br>  git_server:<br>    image: codeberg.org/forgejo/forgejo:15<br>    container_name: forgejo<br>    environment:<br>      - USER_UID=1000<br>      - USER_GID=1000<br>    restart: always<br>    networks:<br>      - forgejo<br>    volumes:<br>      - ./forgejo:/data<br>      - /etc/localtime:/etc/localtime:ro<br>    ports:<br>      - &#39;3000:3000&#39;<br>      - &#39;222:22&#39;<br><br>networks:<br>  forgejo:<br>    external: false</pre><p>Let me quickly explain why we set the variables USER_UID and USER_GID. In short, this is IDs of the user or user group that will own all Forgejo data that will be stored in /data inside the container.</p><p>Now that we have a container configuration, it’s time to build and run a Forgejo instance locally:</p><pre># Run this in the same folder where you have docker-compose.yaml<br>$ docker compose up -d --build</pre><p>In case you won’t use Docker for this setup and you want an open source analog, use <a href="https://podman.io/">Podman</a>, but you will need to save a few additional configuration files into systemd (<a href="https://forgejo.org/docs/latest/admin/installation/docker/#podman">check this in the documentation</a>).</p><p>When Docker finishes building the image and starts the Forgejo container, it will automatically create a “forgejo” folder, where you can do all additional configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*cjtCnmxANe1RgNUzBV1BdA.png" /></figure><p>For example, if you want to change Forgejo database path or engine, you just need to open forgejo/gitea/conf/app.ini (for now, just take a look at this file, no need to edit):</p><pre>APP_NAME = Forgejo: Beyond coding. We forge.<br>RUN_MODE = prod<br><br>[repository]<br>ROOT = /data/git/repositories<br><br>[repository.local]<br>LOCAL_COPY_PATH = /data/gitea/tmp/local-repo<br><br>[repository.upload]<br>TEMP_PATH = /data/gitea/uploads<br><br># You can find here configuration for anything<br># in your local Forgejo instance<br><br>[database]<br>PATH = /data/gitea/gitea.db<br>DB_TYPE = sqlite3<br>HOST    = localhost:3306<br>NAME    = gitea<br>USER    = root<br>PASSWD  = <br>LOG_SQL = false</pre><h4>Switch database engine</h4><p>SQLite3 database engine is good for small pet projects, but it’s bad for production instances; thus, we are going to configure our instance to use PostgreSQL database, and edit the docker-compose.yaml first:</p><pre>services:<br>  git_server:<br>    image: codeberg.org/forgejo/forgejo:15<br>    container_name: forgejo<br>    environment:<br>      - USER_UID=1000<br>      - USER_GID=1000<br>      - FORGEJO__database__DB_TYPE=postgres # No need to edit app.ini directly, you can<br>      - FORGEJO__database__HOST=db:5432     # do all configuration inside the docker-compose.yaml file<br>      - FORGEJO__database__NAME=forgejo<br>      - FORGEJO__database__USER=forgejo<br>      - FORGEJO__database__PASSWD=forgejo<br>    restart: always<br>    networks:<br>      - forgejo<br>    volumes:<br>      - ./forgejo:/data<br>      - /etc/localtime:/etc/localtime:ro<br>    ports:<br>      - &#39;3000:3000&#39;<br>      - &#39;222:22&#39;<br>    depends_on:<br>      - db<br>  <br>  db:<br>    image: postgres:14<br>    restart: always<br>    environment: # REMEMBER: Never use credentials like these in production!<br>      - POSTGRES_USER=forgejo<br>      - POSTGRES_PASSWORD=forgejo<br>      - POSTGRES_DB=forgejo<br>    networks:<br>      - forgejo<br>    volumes:<br>      - ./postgres:/var/lib/postgresql/data<br><br>networks:<br>  forgejo:<br>    external: false</pre><p>Don’t forget to rebuild containers and restart them:</p><pre>$ docker compose down<br>$ docker compose up -d --build</pre><h4>First installation configuration</h4><p>To test if everything went well, just open localhost:3000 in your browser, and you should see the first installation page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*DXBxB-XE2d5xMazV3K0fTw.png" /></figure><p>I showed you a Docker-based configuration, so you have a better picture of how you can configure everything programmatically, as is done in many cases. You can configure SSH, SMTP, ports, server, and an admin account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*qSq7jI9xbqSxie0IQhmQSQ.png" /></figure><p>In our case, we are going to set only admin credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*nrmZnCP_5Kxng5yA0myLug.png" /></figure><p>When you finish the configuration, just click on the “Install Forgejo” button, and it will finish installation.</p><h4>First steps</h4><p>If everything is okay and there are no errors, you should see the following dashboard after finishing installation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOuE_K0IwFRieqkVRRCauA.png" /></figure><p>Like on GitHub, you can start creating your repositories/organization immediately from the profile menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Vi7ALSD1fy7ew-OY07A24w.png" /></figure><h4>Creating a repository and pushing changes</h4><p>Just click the “New repository” button and create your first test repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUiEeCRA2psiT694PanJdw.png" /></figure><p>And boom! That’s all, you successfully created your first repository in Forgejo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8RubSHrWkRAKdNK_58BajA.png" /></figure><p>You can just copy the following commands and execute them in a newly created folder of the repository to push the first commit and link your repository:</p><pre>$ touch README.md<br>$ git init<br>$ git switch -c main<br>$ git add README.md<br>$ git commit -m &quot;first commit&quot;<br>$ git remote add origin http://localhost:3000/myadmin/firstrep.git<br>$ git push -u origin main</pre><p>When you try to push changes or pull from the repository from the Forgejo instance, you will be asked to type your credentials in the terminal for authorization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*kw-lL7cGlxEVFX19ybKeww.png" /></figure><p>When the auth is done, you will see a message that your commit was pushed to the main branch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*q-ewSj15dNbEh8c3zThgwg.png" /></figure><p>Refresh the repository page, and you will see committed changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JL-kfU95QEsie6NTvuJX6A.png" /></figure><p>Easy, just like using GitHub or any other git hosting apps!</p><h4>What if I want to make my Forgejo instance more private?</h4><p>This is a great question that some readers can ask. Let me explain how you can easily change the configuration to make sure that your Forgejo instance has nice privacy. First, you need to change a lot in your instance configuration, open the app.ini file, and make the following changes:</p><pre>; Don&#39;t leak you server data, so enable gzip compression<br>ENABLE_GZIP = true<br><br>[service]<br>; No public registration, only admins can create accounts<br>DISABLE_REGISTRATION = true<br>REQUIRE_SIGNIN_VIEW = true ; only registered can view repositories<br>ALLOW_ONLY_INTERNAL_REGISTRATION = true<br>; No need e-mail confirmation as we disabled public registration<br>REGISTER_EMAIL_CONFIRM = false<br>; Hide sensitive user info<br>NO_REPLY_ADDRESS = noreply@yourcompany.com<br>SHOW_REGISTRATION_BUTTON = false<br><br>[openid]<br>ENABLE_OPENID_SIGNIN = false<br>ENABLE_OPENID_SIGNUP = false<br><br>[federation]<br>ENABLED = false   ; disable ActivityPub federation — keeps activity internal<br><br>[repository]<br>; New repos default to private<br>DEFAULT_PRIVATE     = true<br>FORCE_PRIVATE       = false   ; set true if you never want public repos at all<br><br>[privacy]<br>REMEMBER_ME_LIFETIME = 7      ; 7 days, shorter = less risk if session token leaks<br><br>[picture]<br>DISABLE_GRAVATAR        = true    ; don&#39;t leak email hashes to Gravatar<br>ENABLE_FEDERATED_AVATAR = false<br><br>[log]<br>MODE  = file<br>LEVEL = warn    ; avoid logging sensitive request details at debug/info<br><br>[security]<br>; ... other parameters<br>PASSWORD_HASH_ALGO     = argon2    ; stronger than the default bcrypt<br>MIN_PASSWORD_LENGTH    = 12<br>PASSWORD_COMPLEXITY    = lower,upper,digit,spec<br><br>[session]<br>PROVIDER        = file<br>COOKIE_SECURE   = true   ; requires HTTPS<br>SAME_SITE       = strict<br><br>[other]<br>SHOW_FOOTER_VERSION    = false   ; don&#39;t advertise exact version to attackers<br>SHOW_FOOTER_TEMPLATE_LOAD_TIME = false</pre><p>Don’t forget to rebuild containers after you save the configuration file. To be honest, this is just a small part of what you need to do to make everything safer and more private. There are a lot of other things that need to be done on the software and hardware level to ensure full privacy, but this is another topic that I will not cover in this article.</p><h4>Conclusion</h4><p>Simple and easy, and fully self-hosted — and the main benefit that you get: you control all the data and everything. Make sure that you have enough storage memory on your local machine or VM, or you can even try to set this on a VPS for your team/company. More about Forgejo and other self-hosting tricks I will show in the next articles, where I’m going to explain how to work with encrypted volumes and how they can help you in your life as a developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02a39d688630" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/forgejo-or-a-full-guide-on-how-to-create-a-self-hosted-git-instance-02a39d688630">Forgejo — or a full guide on how to create a self hosted git instance</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel & Design Patterns — Practice Series: Proxy]]></title>
            <link>https://blog.stackademic.com/laravel-design-patterns-practice-series-proxy-1f92cce6bf8d?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f92cce6bf8d</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 03:12:32 GMT</pubDate>
            <atom:updated>2025-12-25T16:13:49.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel &amp; Design Patterns — Practice Series: Proxy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEFVTHZwEkv9jWVDGTnLlw.png" /></figure><p>Welcome back, and this is the third article of the patterns series. We are going to implement a practical structural design pattern — Proxy. So, let’s begin with the theoretical part.</p><h3>Introduction</h3><p>First, let’s see what the definition of the Proxy pattern can tell us:</p><p><strong><em>Proxy</em></strong><em> is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.</em></p><p>And let’s check the UML schema to visualize how it’s working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYDMD8SrVcZ8VKmKJ1mb6Q.png" /></figure><h3>Example of a problem</h3><p>Imagine that you have a database with a lot of different financial data, and in your application, you make a lot of the same requests to receive data that consumes a large amount of resources. In this case, it will be good to implement caching for some requests that fetch data that is rarely changed.</p><h3>Implementation</h3><p>To solve this, we can implement some kind of class that will always be requested before proceeding to the original class that we need — you can imagine that like a guard that does a check. Let’s continue our example, and let’s imagine that we want to have a Redis caching for posts in our application, and instead of always making requests to the database — we can cache this data for 12 hours and retrieve it — and to handle this, we are going to use the Proxy pattern as was mentioned before. So first, let’s create our simple Post model that will be used in the service class later:</p><pre>&lt;?php<br><br>namespace App\Models\Post;<br><br>use Illuminate\Database\Eloquent\Model;<br><br>class Post extends Model<br>{<br>  protected $fillable = [&#39;title&#39;, &#39;content&#39;];<br>}</pre><p>Next, we need to have an actual service to retrieve posts from the database:</p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use App\Models\Post;<br>use Illuminate\Support\Collection;<br><br>class PostService<br>{<br>  public function find(int $id): ?Post<br>  {<br>    return Post::find($id);<br>  }<br>  <br>  public function latest(int $limit = 10): Collection<br>  {<br>    return Post::latest()-&gt;limit($limit)-&gt;get();<br>  }<br>}</pre><p>And finally — PostCache class — that will be our Proxy for caching or getting actual data from the database if we don’t have cached data:</p><pre>&lt;?php<br><br>namespace App\Cache;<br><br>use App\Services\PostService;<br>use App\Models\Post;<br>use Illuminate\Support\Facades\Cache;<br>use Illuminate\Support\Collection;<br><br>class PostCache<br>{<br>  public function __construct(<br>    private PostService $service<br>  ) {}<br>  <br>  public function find(int $id): ?Post<br>  {<br>    // As you can see, when there is no cached post<br>    // we request again actual data from service<br>    return Cache::remember(<br>      &quot;posts:{$id}&quot;,<br>      now()-&gt;addMinutes(10),<br>      fn () =&gt; $this-&gt;service-&gt;find($id)<br>    );<br>  }<br>  <br>  public function latest(int $limit = 10): Collection<br>  {<br>    return Cache::remember(<br>      &quot;posts:latest:{$limit}&quot;,<br>      now()-&gt;addMinutes(5),<br>      fn () =&gt; $this-&gt;service-&gt;latest($limit)<br>    );<br>  }<br>  <br>  public function forgot(int $id): void<br>  {<br>    Cache::forget(&quot;posts:{$id}&quot;);<br>    Cache::forget(&quot;posts:latest:*&quot;);<br>  }<br>}</pre><p>And finally, let’s create a controller to use it:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Cache\PostCache;<br><br>class PostController<br>{<br>  public function __construct(<br>    private PostCache $cache<br>  ) {}<br>  <br>  public function index()<br>  {<br>    $posts = $postCache-&gt;latest();<br>    return response()-&gt;json($posts);<br>  }<br>  <br>  public function show(int $id)<br>  {<br>    $post = $postCache-&gt;find($id);<br>    return response()-&gt;json($post);<br>  }<br>}</pre><h3>Conclusion</h3><p>As you can see, it’s pretty easy to use the proxy pattern, and it’s very useful when you want to use it in caching to implement it with the cache-aside pattern with Redis or Memcached.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f92cce6bf8d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-design-patterns-practice-series-proxy-1f92cce6bf8d">Laravel &amp; Design Patterns — Practice Series: Proxy</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel & Design Patterns — Practice Series: Adapter]]></title>
            <link>https://blog.stackademic.com/laravel-design-patterns-practice-series-adapter-d6ba85762c52?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6ba85762c52</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 12:01:48 GMT</pubDate>
            <atom:updated>2025-09-17T07:56:06.001Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel &amp; Design Patterns — Practice Series: Adapter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJjB1g-aydV0jAuK4rLM3Q.png" /></figure><p>Welcome back, this is the next article in our practical use of patterns in Laravel, and in this guide, we are going to talk about one of the most popular patterns that is used across many developers — and this is the Adapter pattern.</p><h3><strong>Introduction</strong></h3><p>Let’s begin with the definition of Adapter:</p><blockquote><em>Adapter pattern </em>- is a <strong>structural design pattern </strong>that allows objects with incompatible interfaces to work together by translating one interface into another that a client expects.</blockquote><h3><strong>Real-world example</strong></h3><p>Imagine that you’re traveling from the US to the EU, and when you arrive at your hotel, you find out that in the EU, people use a different type of socket to use their electronic devices. And to solve this problem, you but a socket adapter to easily charge your devices with your US plug.</p><h3><strong>Bad example (anti-pattern)</strong></h3><p>First, let’s see what a bad solution looks like without using any adapter classes and without any clean code architecture:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use Stripe\StripeClient;<br>use Square\SquareClient;<br>use Square\Models\Money;<br>use Square\Models\CreatePaymentRequest;<br><br>class BadCheckoutController extends Controller<br>{<br>    public function store(Request $request)<br>    {<br>        // We get a lot of data from $request without any processing, which can create<br>        // a lot of issues in the future for transactions processing<br>        $gateway = $request-&gt;string(&#39;gateway&#39;);<br>        $amount  = (float) $request-&gt;input(&#39;amount&#39;);<br>        $currency = $request-&gt;input(&#39;currency&#39;, &#39;USD&#39;);<br>        $pm = $request-&gt;string(&#39;payment_method&#39;);<br><br>        // Another bad practice - is to use conditions for creating new class objects with hardcoded actions<br>        if ($gateway === &#39;stripe&#39;) {<br>            $stripe = new StripeClient(config(&#39;services.stripe.secret&#39;));<br><br>            $intent = $stripe-&gt;paymentIntents-&gt;create([<br>                &#39;amount&#39; =&gt; (int) round($amount),<br>                &#39;currency&#39; =&gt; strtolower($currency),<br>                &#39;payment_method&#39; =&gt; $pm,<br>                &#39;confirm&#39; =&gt; true,<br>                &#39;description&#39; =&gt; $request-&gt;input(&#39;description&#39;, &#39;Order #&#39;.now()-&gt;timestamp),<br>            ]);<br><br>          <br>            if ($intent-&gt;status !== &#39;succeeded&#39;) {<br>                return back()-&gt;withErrors([&#39;payment&#39; =&gt; &#39;Stripe failed: &#39;.$intent-&gt;status]);<br>            }<br><br>            // All this business logic in controller will create another issues<br>            return redirect()-&gt;route(&#39;thankyou&#39;)-&gt;with(&#39;tx&#39;, $intent-&gt;id);<br>        } elseif ($gateway === &#39;square&#39;) {<br>            $square = new SquareClient([<br>                &#39;accessToken&#39; =&gt; config(&#39;services.square.access_token&#39;),<br>                &#39;environment&#39; =&gt; config(&#39;services.square.environment&#39;, &#39;sandbox&#39;),<br>            ]);<br><br>            $paymentsApi = $square-&gt;getPaymentsApi();<br><br>            $money = new Money();<br>            $money-&gt;setAmount((int) ($amount * 100.0));<br>            $money-&gt;setCurrency(strtoupper($currency));<br><br>            $requestObj = new CreatePaymentRequest(<br>                sourceId: $pm,<br>                idempotencyKey: (string) rand(),<br>                amountMoney: $money<br>            );<br><br>            try {<br>                $response = $paymentsApi-&gt;createPayment($requestObj);<br>                if ($response-&gt;isSuccess()) {<br>                    $payment = $response-&gt;getResult()-&gt;getPayment();<br>                    if ($payment-&gt;getStatus() !== &#39;COMPLETED&#39;) {<br>                        return back()-&gt;withErrors([&#39;payment&#39; =&gt; &#39;Square not completed: &#39;.$payment-&gt;getStatus()]);<br>                    }<br>                    return redirect()-&gt;route(&#39;thankyou&#39;)-&gt;with(&#39;tx&#39;, $payment-&gt;getId());<br>                }<br><br>                $errs = collect($response-&gt;getErrors() ?? [])-&gt;map(fn($e) =&gt; $e-&gt;getDetail() ?: &#39;error&#39;)-&gt;implode(&#39;; &#39;);<br>                return back()-&gt;withErrors([&#39;payment&#39; =&gt; &#39;Square failed: &#39;.$errs]);<br>            } catch (\Throwable $e) {<br>                return back()-&gt;withErrors([&#39;payment&#39; =&gt; &#39;Square error: &#39;.$e-&gt;getMessage()]);<br>            }<br><br>            return back()-&gt;withErrors([&#39;payment&#39; =&gt; &#39;Unknown gateway&#39;]);<br>        }<br>    }<br>}</pre><p>Looks very ugly 0.0 Now it’s time to separate all logic properly with best practices, and to solve it — we are going to use the Adapter pattern.</p><h3><strong>Adapter pattern implementation</strong></h3><p>First of all, we need to define an interface that will be used by our adapter classes to properly handle different payment systems with the same function:</p><pre>&lt;?php<br><br>namespace App\Domains\Payment;<br><br>interface PaymentGateawayInterface<br>{<br>    public function charge(<br>        int $amount,<br>        string $currency,<br>        string $source,<br>        string $description = &#39;&#39;       <br>    );<br>}</pre><p>Also, don’t forget to install the payment library with Composer into the Laravel project:</p><pre>$ composer require stripe/stripe-php</pre><p>After dependencies are installed, we also need to define a class where we are going to store transaction results</p><pre>&lt;?php<br><br>namespace App\Domains\Payment;<br><br>class ChargeResult<br>{<br>    public function __construct(<br>        public bool $success,<br>        public string $transactionId,<br>        public string $message,<br>    ) {}<br>}</pre><p>Now that the main components are defined, it’s time to create our first adapter to handle Stripe transactions:</p><pre>&lt;?php<br><br>namespace App\Domains\Payment;<br><br>use Stripe\StripeClient;<br>use Exception;<br><br>class StripeGateawayAdapter implements PaymentGateawayInterface<br>{<br>    // We use dependency injection to properly handle<br>    // object creation from the framework side<br>    public function __construct(<br>        private StripeClient $client<br>    ) {}<br><br>    public function charge(<br>        int $amount,<br>        string $currency,<br>        string $source,<br>        string $description = &#39;&#39;<br>    ) {<br>        try {<br>            $response = $this-&gt;client-&gt;paymentIntents-&gt;create([<br>                &#39;amount&#39; =&gt; $amount,<br>                &#39;currency&#39; =&gt; $currency,<br>                &#39;payment_method&#39; =&gt; $source,<br>                &#39;confirm&#39; =&gt; true,<br>                &#39;description&#39; =&gt; $description<br>            ]);<br><br>            return new ChargeResult(<br>                success: $response-&gt;status === &#39;succeeded&#39;,<br>                transactionId: $response-&gt;id,<br>                message: $response-&gt;status<br>            );<br>        } catch( Exception $e ) {<br>            return new ChargeResult(<br>                success: false,<br>                transactionId: null,<br>                message: $e-&gt;getMessage()<br>            );<br>        }<br>    }<br>}</pre><p>But, that&#39;s not the only adapter class that we need to create; we will also create an adapter to handle Square payment system transactions:</p><pre>&lt;?php<br><br>namespace App\Domains\Payment;<br><br>use Exception;<br>use Square\Payments\Requests\CreatePaymentRequest;<br>use Square\Legacy\Models\Money;<br>use Square\SquareClient;<br>use Illuminate\Support\Str;<br><br>class SquareGateawayAdapter implements PaymentGateawayInterface<br>{<br>    public function __construct(<br>        private SquareClient $client<br>    ) {}<br><br>    public function charge(<br>        int $amount,<br>        string $currency,<br>        string $source,<br>        string $description = &#39;&#39;<br>    ) {<br>        $money = new Money();<br>        $money-&gt;setAmount($amount);<br>        $money-&gt;setCurrency(strtoupper($currency));<br><br>        $request = new CreatePaymentRequest([<br>            &#39;idempotencyKey&#39; =&gt; Str::uuid()-&gt;toString(),<br>            &#39;sourceId&#39; =&gt; $source,<br>            &#39;amountMoney&#39; =&gt; $money<br>        ]);<br><br>        if ($description !== &#39;&#39;) {<br>            $request-&gt;setNote($description);<br>        }<br><br>        try {<br>            $response = $this-&gt;client-&gt;payments-&gt;create(<br>                $request<br>            );<br><br>            if ( $response-&gt;getPayment() ) {<br>                // ... return success here<br>            }<br>        } catch ( Exception $e ) {<br>            return new ChargeResult(<br>                success: false,<br>                transactionId: null,<br>                message: $e-&gt;getMessage(),<br>            );<br>        }<br>    }<br>}</pre><p>That looks much better now with using adapters; our code is now cleaner, readable, and we follow SOLID principles with OOP. And of course, if we are using any interface in the Laravel framework, we also need to bind it properly in the AppServiceProvider.php:</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use App\Domains\Payment\PaymentGateawayInterface;<br>use App\Domains\Payment\SquareGateawayAdapter;<br>use App\Domains\Payment\StripeGateawayAdapter;<br>use Illuminate\Support\ServiceProvider;<br>use App\Domains\Report\Builders\IReportBuilder;<br>use App\Domains\Report\Builders\ReportBuilder;<br><br>class AppServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register any application services.<br>     */<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;bind(PaymentGateawayInterface::class, StripeGateawayAdapter::class);<br>        $this-&gt;app-&gt;bind(PaymentGateawayInterface::class, SquareGateawayAdapter::class);<br>    }<br><br>    /**<br>     * Bootstrap any application services.<br>     */<br>    public function boot(): void<br>    {<br>        //<br>    }<br>}</pre><p>Amazing, now we can easily use it in our controllers easily:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Domains\Payment\StripeGateawayAdapter;<br>use App\Domains\Payment\SquareGateawayAdapter;<br>use App\Domains\Payment\PaymentGateawayInterface;<br>use Stripe\StripeClient;<br>use Square\SquareClient;<br><br><br>class CheckoutController extends Controller<br>{<br>    private PaymentGateawayInterface $gateway;<br><br>    public function __construct()<br>    {<br>        // We will have config for all payments<br>        $driver = config(&#39;payments.driver&#39;, &#39;stripe&#39;);<br><br>        // Dynamically switch gateaway payment based on config<br>        // we can also move this code to service file<br>        $this-&gt;gateway = match ($driver) {<br>            &#39;stripe&#39; =&gt; new StripeGateawayAdapter(<br>                new StripeClient(config(&#39;services.stripe.secret&#39;))<br>            ),<br>            &#39;square&#39; =&gt; new SquareGateawayAdapter(<br>                new SquareClient([<br>                    &#39;accessToken&#39; =&gt; config(&#39;services.square.access_token&#39;),<br>                    &#39;environment&#39; =&gt; config(&#39;services.square.environment&#39;),<br>                ])<br>            ),<br>            default =&gt; throw new \RuntimeException(&quot;Unknown payment driver [$driver]&quot;),<br>        };<br>    }<br><br>    public function store(Request $request)<br>    {<br>        $result = $this-&gt;gateway-&gt;charge(<br>            (int) ($request-&gt;input(&#39;amount&#39;) * 100),<br>            $request-&gt;input(&#39;currency&#39;, &#39;USD&#39;),<br>            $request-&gt;input(&#39;payment_method&#39;),<br>            &#39;Order #&#39; . now()-&gt;timestamp<br>        );<br><br>        if (! $result-&gt;success) {<br>            return back()-&gt;withErrors([&#39;payment&#39; =&gt; $result-&gt;message]);<br>        }<br><br>        return redirect()<br>            -&gt;route(&#39;thankyou&#39;)<br>            -&gt;with(&#39;tx&#39;, $result-&gt;transactionId);<br>    }<br>}</pre><h3><strong>Conclusion</strong></h3><p>Now our code is much cleaner and readable, and of course, we follow SOLID principles. Remember, in cases when you have any external library or classes that are not compatible with your interface, you can use the Adapter pattern to easily implement them into your code and separate all logic properly. Thanks for reading!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6ba85762c52" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-design-patterns-practice-series-adapter-d6ba85762c52">Laravel &amp; Design Patterns — Practice Series: Adapter</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel & Design Patterns — Practice Series: Facade]]></title>
            <link>https://blog.stackademic.com/laravel-design-patterns-practice-series-facade-ce1c0598d177?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce1c0598d177</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 12:01:42 GMT</pubDate>
            <atom:updated>2025-09-17T07:55:12.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel &amp; Design Patterns — Practice Series: Facade</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpZl3Y5EQRvvBSp1iw-Q_g.png" /></figure><p>In this article, we are going to take a look at how to practically implement the most used patterns in Laravel — the Facade pattern. So, as always, let’s begin with a definition.</p><p><strong><em>Facade </em></strong><em>— is a structural design pattern that provides a simplified interface to a library, a framework, or any other complex set of classes.</em></p><p>Just imagine that you have installed a custom mailing library into your application that requires object initialization and other function calls to send email. And instead of creating a library class object again and again, and calling all other tasks that you need for sending email, you just create a simple facade class where you will do all this stuff in one function, without the need to work with the library directly.</p><h3>Introduction</h3><p>For this article, we are going to install a real library just to demonstrate how you can use this pattern for such cases, so run the following command:</p><pre>$ composer require league/flysystem</pre><p>This is a great abstraction package for working with local or remote storage, and now let’s see a bad example without a facade implementation.</p><h3>Bad example</h3><p>Let’s imagine that we will need to save our file in our controller into local and remote storage using this library in the controller called FileController:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use League\Flysystem\Local\LocalFilesystemAdapter;<br>use League\Flysystem\Filesystem;<br>use League\Flysystem\FileAttributes;<br>use Exception;<br><br>class FileController extends Controller<br>{<br>    public function createFileWithList(Request $request)<br>    {<br>        $path = __DIR__ . &#39;/storage&#39;;<br>        $adapter = new LocalFilesystemAdapter($path);<br>        $filesystem = new Filesystem($adapter);<br>      <br>        // Save file into our local storage<br>        try {<br>            $filesystem-&gt;write(location: &#39;example.txt&#39;, contents: &#39;Lorem ipsum dolor sit amet.&#39;);<br>        } catch (Exception $e) {<br>            throw new Exception(&quot;Something went wrong with file upload: &quot; . $e-&gt;getMessage());<br>        }<br><br>        // Get files list from storage<br>        $listing = $filesystem-&gt;listContents($path);<br>      <br>        foreach ($listing as $item) {<br>            $itemPath = $item-&gt;path();<br>            if ($item instanceof FileAttributes) {<br>                echo &quot;File: $itemPath\n&quot;;<br>            } else if ($item instanceof DirectoryAttributes) {<br>                echo &quot;Directory: $itemPath\n&quot;;<br>            }<br>        }<br>    }<br>}</pre><p>As you can see here, we do a lot of different imports and create two different objects to handle file upload and file listing, and also we do “try catch” for the write function, and make another call to foreach all files and directories from our storage. In our case, each time we want just to save a file, we will need to specify the storage path, create new class objects, and again call <em>the write()</em> function — that’s not good.</p><p>And this is the case when we should use the Facade pattern to separate library functionality that we need into a separate class that we are going to use for such cases.</p><h3>Facade pattern implementation</h3><p>Now it’s time to do everything correctly. First, create a new file in <em>app/Facades/FileFacade.php</em> — that will be our facade class that will be used for file upload with that library:</p><pre>&lt;?php<br><br>namespace App\Domains\Facades;<br><br>use League\Flysystem\Local\LocalFilesystemAdapter;<br>use League\Flysystem\Filesystem;<br>use League\Flysystem\FileAttributes;<br>use Exception;<br><br>class FileFacade<br>{<br>    private $path;<br>    private LocalFilesystemAdapter $adapter;<br>    private Filesystem $filesystem;<br><br>    public function __construct()<br>    {<br>        $this-&gt;path = storage_path(&#39;app/files&#39;);<br>        $this-&gt;adapter = new LocalFilesystemAdapter($this-&gt;path);<br>        $this-&gt;filesystem = new Filesystem($this-&gt;adapter);<br>    }<br><br>    public function createFile($name, $content)<br>    {<br>        $this-&gt;filesystem-&gt;write(location: $name, contents: $content);<br>    }<br><br>    public function getFilesList()<br>    {<br>        $listing = $this-&gt;filesystem-&gt;listContents($this-&gt;path);<br><br>        foreach ($listing as $item) {<br>            $itemPath = $item-&gt;path();<br><br>            if ($item instanceof FileAttributes) {<br>                echo &quot;File: $itemPath\n&quot;;<br>            } else if ($item instanceof DirectoryAttributes) {<br>                echo &quot;Directory: $itemPath\n&quot;;<br>            }<br>        }<br>    }<br>}</pre><p>Pay attention that for each operation we created a separate function, so in the future we can easily reuse it in our codebase. Now it’s time to rewrite <em>FileController</em> in the right way by using the facade that we just created:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Domains\Facades\FileFacade;<br><br>class FileController extends Controller<br>{<br>    public function __construct(<br>        private FileFacade $fileFacade<br>    ) {}<br><br>    public function createFileWithList(Request $request)<br>    {<br>        // also we can provide values from $request for this function<br>        $this-&gt;fileFacade-&gt;createFile(&#39;test.txt&#39;, &#39;my super file&#39;);<br>        $this-&gt;fileFacade-&gt;getFilesList();<br>    }<br>}</pre><p>Don’t forget to add an endpoint for this controller in your <em>routes/web.php</em>:</p><pre>&lt;?php<br><br>use App\Http\Controllers\FileController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/file/create&#39;, [FileController::class, &#39;createFileWithList&#39;]);</pre><p>Visit this page and check the<em> storage/app/files</em> folder — and you will see that the file was created, which means that our implementation is working properly. We separated our controller from direct interaction with the library and also removed dependency on the library — that’s a good approach.</p><h3>Inside Laravel examples</h3><p>Now that you have understood what is facade pattern is and how it can be used in development, let’s see some examples of some Laravel classes that are being used frequently by developers. First example — Http facade:</p><pre>&lt;?php<br><br>namespace App\Domains\Facades;<br><br>use Illuminate\Support\Facades\Http;<br><br>class GetPostsCommand<br>{<br>    private $api = &#39;https://jsonplaceholder.typicode.com/&#39;;<br><br>    public function execute()<br>    {<br>        $response = Http::get($this-&gt;api.&#39;/posts&#39;);<br><br>        return $response-&gt;getBody();<br>    }<br>}</pre><p>Basically, we just did a GET HTTP request using the get() function from the Http facade, and the most interesting thing is that Laravel, in the Http class, is using the Guzzle HTTP library, and to make use of this class easier and simpler, it’s using the facade pattern.</p><p>And that’s not the only example of Laravel classes that use this pattern; all classes that are in Illuminate\Support\Facades namespace - are classes with implemented Facade pattern.</p><h3>Conclusion</h3><p>This was a simple but practical example of how to use Facade in your Laravel application, pretty easy and nice, which makes your code cleaner and easier for modifications.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce1c0598d177" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-design-patterns-practice-series-facade-ce1c0598d177">Laravel &amp; Design Patterns — Practice Series: Facade</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel & Design Patterns — Practice Series: Builder]]></title>
            <link>https://blog.stackademic.com/laravel-design-patterns-practice-series-builder-c803d6bbf1fd?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c803d6bbf1fd</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 12:01:58 GMT</pubDate>
            <atom:updated>2025-09-17T07:54:33.889Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel &amp; Design Patterns — Practice Series: Builder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkIXXORfmgSEoz-ETRzjnQ.png" /></figure><p>I was tired of seeing how many articles repeat again and again basic examples of using design patterns in development, examples based on shape figures/real-life objects are good for understanding when you are just start learning this concept of design patterns. But what about real practice? What about real examples with real code and frameworks to get a much better practical understanding and use?</p><p>And this is the reason why I decided to start writing a series of articles about full practice in the Laravel framework. Even if you’re not a PHP developer and you have some medium-level experience in web development, you still can understand what we are going to do, and use it in your own development.</p><h3>Builder pattern: Introduction</h3><p>It was a good decision to start this series with one of the simplest patterns, named “builder” from the creational patterns. Let’s begin with some graphical examples to remember how it works, and after that, let’s move on to writing some code for generating reports in different file formats.</p><p>Let’s begin with a definition:</p><blockquote>The <strong>Builder</strong> design pattern is a creational pattern that separates the construction of a complex object from its representation, allowing the same construction process to create different representations. It is especially useful when an object needs to be created with many optional parts or configurations.</blockquote><h3>Real-life example</h3><p>A simple real-life example of the Builder Pattern is how you order a burger at a fast-food restaurant:<br>- Instead of giving you only fixed menu items, the restaurant lets you customize your burger.<br>- You can add a patty, cheese, lettuce, tomato, sauces, bacon, etc., in the order you like.<br>- The builder (the person assembling) constructs the burger step by step.<br>- At the end, you get a fully built burger according to your specifications.</p><p>🥩 + 🧀 + 🥬 + 🍅 + 🍞 ➝ 🍔</p><h3>UML Representation</h3><p>Now, let’s take a quick look at the abstract UML schema to understand how we should build our classes&#39; interaction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*gAPQb5ji3GAzrbbb4qHQcA.png" /></figure><p>Here is an explanation of how this UML schema works:</p><ul><li>Everything begins with Interface <em>IBuilder</em>, which defines a typical <em>build()</em> method, which will be used in the concrete class implementation for building the final class object</li><li>Next, what comes after this is <em>ObjectBuilder</em>, a class with a concrete implementation of how a class object can be built. There can be different methods, not only the concrete implementation of the <em>build() </em>method</li><li><em>TargetObject</em> — is the final product of the object that we will get from our builder</li><li>And in case we want, we can extend our builder and have a lot of <em>OtherObject</em></li></ul><p>This abstraction gives to use power for encapsulation of object creation in our builder, which makes your Laravel code cleaner, modular, and easier for extension or any modification.</p><p>Let’s now take a look at a more concrete UML implementation, and after that, we are going to begin using this design pattern in the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*IFpPSAJg-aD7dXj4nKa2gA.png" /></figure><p>I hope that this picture will give you more understanding of how the builder pattern is working, and that’s what we are going to do now, we are going to use this pattern to create a report creation solution. Let’s begin.</p><h3>Implementation</h3><p>First, take a look at how our structure will be organized:</p><pre>app/<br>└── Services/<br>    └── Report/<br>        ├── Builders/<br>        │   ├── IReportBuilder.php<br>        │   ├── ReportBuilder.php<br>        ├── Formats/<br>        │   ├── Formatter.php<br>        │   ├── PDFReport.php<br>        │   ├── JSONReport.php<br>        └── ReportService.php</pre><p>Of course, if you want, you can follow the DDD (Domain-Driven-Design) principle, and then your structure will look like this:</p><pre>app/<br>└── Domains/<br>    └── Report/<br>        ├── Builders/<br>        │   ├── IReportBuilder.php # Our interface<br>        │   ├── ReportBuilder.php<br>        ├── Formats/<br>        │   ├── Formatter.php<br>        │   ├── PDFReport.php<br>        │   ├── JSONReport.php<br>        └── Report.php</pre><p>When we get the full picture of how our structure will look, we can start building and create a report entity in Report.php:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Entities;<br><br>class Report<br>{<br>    public function __construct(<br>        public string $title = &#39;&#39;,<br>        public ?array $period = null,<br>        public array $rows = [],<br>        public array $totals = []<br>    ) {}<br><br>    public function toArray(): array<br>    {<br>        return [<br>            &#39;title&#39; =&gt; $this-&gt;title,<br>            &#39;period&#39; =&gt; $this-&gt;period,<br>            &#39;rows&#39; =&gt; $this-&gt;rows,<br>            &#39;totals&#39; =&gt; $this-&gt;totals<br>        ];<br>    }<br>}</pre><p>Next, let’s now define our interface IBuilderInterface that will be used for our report builder:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Builders;<br><br>use App\Domains\Report\Entities\Report;<br>use App\Domains\Report\Formats\Formatter;<br><br>interface IReportBuilder<br>{<br>    public function reset(): static;<br><br>    public function setTitle(string $title): static;<br><br>    public function setPeriod(?array $period): static;<br><br>    public function setRows(array $rows): static;<br><br>    public function addRow(array $row): static;<br><br>    public function setTotals(array $totals): static;<br><br>    public function setFormatter(Formatter $formatter): static;<br><br>    public function getReport(): Report;<br><br>    public function build();<br>}</pre><p>Okay, now we need to define the Formatter interface that will be used for our Format classes:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Formats;<br><br>use App\Domains\Report\Entities\Report;<br><br>interface Formatter<br>{<br>    public function render(Report $report);<br>}</pre><p>After this, let’s create our first format class — and it will be JsonReport:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Formats;<br><br>use App\Domains\Report\Formats\Formatter;<br>use App\Domains\Report\Entities\Report;<br><br>class JsonReport implements Formatter<br>{<br>    public function render(Report $report)<br>    {<br>        return response()<br>            -&gt;json($report-&gt;toArray());<br>    }<br>}</pre><p>And let’s also add another class that will be used to create a report in XML format:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Formats;<br><br>use App\Domains\Report\Entities\Report;<br><br>class XMLReport implements Formatter<br>{<br>    public function render(Report $report)<br>    {<br>        $xml = new \SimpleXMLElement(&#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;report&gt;&lt;/report&gt;&#39;);<br><br>        $xml-&gt;addChild(&#39;title&#39;, $report-&gt;title);<br><br>        if ($report-&gt;period) {<br>            $periodNode = $xml-&gt;addChild(&#39;period&#39;);<br>            $periodNode-&gt;addChild(&#39;from&#39;, $report-&gt;period[&#39;from&#39;] ?? &#39;&#39;);<br>            $periodNode-&gt;addChild(&#39;to&#39;, $report-&gt;period[&#39;to&#39;] ?? &#39;&#39;);<br>        }<br><br>        $rowsNode = $xml-&gt;addChild(&#39;rows&#39;);<br>        foreach ($report-&gt;rows as $row) {<br>            $rowNode = $rowsNode-&gt;addChild(&#39;row&#39;);<br>            foreach ($row as $key =&gt; $val) {<br>                $rowNode-&gt;addChild($key, htmlspecialchars((string) $val));<br>            }<br>        }<br><br>        if (!empty($report-&gt;totals)) {<br>            $totalsNode = $xml-&gt;addChild(&#39;totals&#39;);<br>            foreach ($report-&gt;totals as $key =&gt; $val) {<br>                $totalsNode-&gt;addChild($key, (string) $val);<br>            }<br>        }<br><br>        return response($xml-&gt;asXML(), 200, [<br>            &#39;Content-Type&#39; =&gt; &#39;application/xml&#39;,<br>        ]);<br>    }<br>}</pre><p>Amazing, and the main class that will be used to build the report following the Builder pattern — this is ReportBuilder:</p><pre>&lt;?php<br><br>namespace App\Domains\Report\Builders;<br><br>use App\Domains\Report\Builders\IReportBuilder;<br>use App\Domains\Report\Entities\Report;<br>use App\Domains\Report\Formats\Formatter;<br><br>class ReportBuilder implements IReportBuilder<br>{<br>    protected Report $report;<br><br>    protected ?Formatter $formatter = null;<br><br>    public function __construct()<br>    {<br>        $this-&gt;reset();<br>    }<br><br>    public function reset(): static<br>    {<br>        $this-&gt;report = new Report();<br>        return $this;<br>    }<br><br>    public function setTitle(string $title): static<br>    {<br>        $this-&gt;report-&gt;title = $title;<br>        return $this;<br>    }<br><br>    public function setPeriod(?array $period): static<br>    {<br>        $this-&gt;report-&gt;period = $period;<br>        return $this;<br>    }<br><br>    public function setRows(array $rows): static<br>    {<br>        $this-&gt;report-&gt;rows = $rows;<br>        return $this;<br>    }<br><br>    public function addRow(array $row): static<br>    {<br>        $this-&gt;report-&gt;rows[] = $row;<br>        return $this;<br>    }<br><br>    public function setTotals(array $totals): static<br>    {<br>        $this-&gt;report-&gt;totals = $totals;<br>        return $this;<br>    }<br><br>    public function setFormatter(Formatter $formatter): static<br>    {<br>        $this-&gt;formatter = $formatter;<br>        return $this;<br>    }<br><br>    public function getReport(): Report<br>    {<br>        return $this-&gt;report;<br>    }<br><br>    public function build()<br>    {<br>        $response = $this-&gt;formatter-&gt;render($this-&gt;report);<br>        $this-&gt;reset();<br><br>        return $response;<br>    }<br>}</pre><p>Before we are going to test how it’s working in the controller, we also need to register in the container our IBuilderInterface with the ReportBuilder class in app/Providers/AppServiceProvider.php:</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use Illuminate\Support\ServiceProvider;<br>use App\Domains\Report\Builders\IReportBuilder;<br>use App\Domains\Report\Builders\ReportBuilder;<br><br>class AppServiceProvider extends ServiceProvider<br>{<br>    /**<br>     * Register any application services.<br>     */<br>    public function register(): void<br>    {<br>        $this-&gt;app-&gt;bind(IReportBuilder::class, ReportBuilder::class);<br>    }<br><br>    /**<br>     * Bootstrap any application services.<br>     */<br>    public function boot(): void<br>    {<br>        //<br>    }<br>}</pre><p>Almost done, now we should create a new controller — ReportController:</p><pre>$ php artisan make:controller ReportController</pre><p>Finally, let’s use our ReportBuilder to create a JSON report:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Domains\Report\Builders\ReportBuilder;<br>use App\Domains\Report\Formats\JsonReport;<br>use App\Domains\Report\Formats\XMLReport;<br>use Illuminate\Http\Request;<br><br>class ReportController extends Controller<br>{<br>    public function __construct(<br>        private ReportBuilder $reportBuilder<br>    ) {}<br><br>    public function getReport(Request $request, string $type)<br>    {<br>        $rows = [<br>            [&#39;date&#39; =&gt; &#39;2025-08-01&#39;, &#39;orders&#39; =&gt; 12, &#39;revenue&#39; =&gt; 3400],<br>            [&#39;date&#39; =&gt; &#39;2025-08-02&#39;, &#39;orders&#39; =&gt; 9,  &#39;revenue&#39; =&gt; 2210],<br>        ];<br><br>        $totals = [<br>            &#39;orders&#39;  =&gt; array_sum(array_column($rows, &#39;orders&#39;)),<br>            &#39;revenue&#39; =&gt; array_sum(array_column($rows, &#39;revenue&#39;)),<br>        ];<br><br>        $period = [&#39;from&#39; =&gt; &#39;2025-08-01&#39;, &#39;to&#39; =&gt; &#39;2025-08-02&#39;];<br><br>        $formats = [<br>            &#39;json&#39; =&gt; JsonReport::class,<br>            &#39;xml&#39; =&gt; XMLReport::class,<br>        ];<br><br>        // Get selected formatter<br>        $formatter = app()-&gt;make($formats[$type]);<br><br>        $report = $this-&gt;reportBuilder<br>            -&gt;reset()<br>            -&gt;setTitle(&#39;JSON Report&#39;)<br>            -&gt;setPeriod($period)<br>            -&gt;setRows($rows)<br>            -&gt;setTotals($totals)<br>            -&gt;setFormatter($formatter)<br>            -&gt;build();<br>        <br>        return $report;<br>    }<br>}</pre><p>So, we just created a flexible class to set all report data just by using special functions and following the Builder design pattern, and of course, we can easily select a format by creating separate classes that are responsible for report formats (remember about SOLID principles and try always to write your code clean).</p><p>Don’t forget also to include your report controller in routes/web.php to test how it works in the browser:</p><pre>&lt;?php<br><br>use Illuminate\Support\Facades\Route;<br>use App\Http\Controllers\ReportController;<br><br><br>Route::get(&#39;/report/{type}&#39;, [ReportController::class, &#39;getReport&#39;]);</pre><h3>Conclusion</h3><p>As we can see, it’s easy and nice to use this pattern in case if you want to create objects of some classes flexible and with easy to customize. Laravel has a lot of internal classes that use this pattern for object creation (for example, DB, Mailable, and Http).</p><p>In the next series, we are going to check other creational patterns with practical examples in Laravel, thanks for reading!</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c803d6bbf1fd" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-design-patterns-practice-series-builder-c803d6bbf1fd">Laravel &amp; Design Patterns — Practice Series: Builder</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel and RabbitMQ — Quick setup for processing queues]]></title>
            <link>https://blog.stackademic.com/laravel-and-rabbitmq-quick-setup-for-processing-queues-44f74479062a?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/44f74479062a</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 07:31:34 GMT</pubDate>
            <atom:updated>2025-01-06T05:56:24.744Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel and RabbitMQ — Quick setup for processing queues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vz_LyBxE7n2M6Ked_h965Q.png" /></figure><p>One of the best ways to process queues in Laravel (and even send them to other microservices) — is to use RabbitMQ as a queue worker. If you don’t know what RabbitMQ is, let me explain briefly. RabbitMQ is a very powerful message broker you can use for queue processing, microservices communication, and real-time messaging.</p><h3>Introduction</h3><p>As always, let’s begin our journey by creating a new Laravel project by using the terminal:</p><pre>$ composer create-project laravel/laravel project-name-here</pre><p>After project creation don’t forget to install a popular package that is used to organize all work with RabbitMQ quickly:</p><pre>$ composer require vladimir-yuldashev/laravel-queue-rabbitmq</pre><h3>Configuration setup</h3><p>Before we are going to create the first job and start the queue worker, we need to configure a connection between the application and the RabbitMQ server (don’t forget to start the local RabbitMQ server — more info on the <a href="https://www.rabbitmq.com/docs/download">official documentation</a>):</p><pre>&lt;?php<br><br>return [<br>  // ...<br>  &#39;connections&#39; =&gt; [<br>    &#39;rabbitmq&#39;  =&gt; [<br>      &#39;driver&#39; =&gt; &#39;rabbitmq&#39;,<br>      &#39;hosts&#39;  =&gt; [<br>        [<br>          &#39;host&#39; =&gt; env(&#39;RABBITMQ_HOST&#39;, &#39;127.0.0.1&#39;),<br>          &#39;port&#39; =&gt; env(&#39;RABBITMQ_PORT&#39;, 5672),<br>          &#39;user&#39; =&gt; env(&#39;RABBITMQ_USER&#39;, &#39;guest&#39;),<br>          &#39;password&#39; =&gt; env(&#39;RABBITMQ_PASSWORD&#39;, &#39;guest&#39;),<br>          &#39;vhost&#39; =&gt; env(&#39;RABBITMQ_VHOST&#39;, &#39;/&#39;),<br>        ],<br>      ],<br>    ],<br>  ],<br>];</pre><p>Also, we should update the “.env” file with all credentials for RabbitMQ connection:</p><pre>QUEUE_CONNECTION=rabbitmq<br>RABBITMQ_HOST=127.0.0.1<br>RABBITMQ_PORT=5672<br>RABBITMQ_USER=guest<br>RABBITMQ_PASSWORD=guest<br>RABBITMQ_VHOST=/</pre><h3>Creating a job</h3><p>Boom 💥 ! Time to create a job that will process all RabbitMQ stuff:</p><pre>$ php artisan make:job ProcessMessage</pre><p>Open “App/Jobs/ProcessMessage.php” and let’s log some messages to see that our RabbitMQ queue processing is working:</p><pre>&lt;?php<br><br>namespace App\Jobs;<br><br>use Illuminate\Bus\Queueable;<br>use Illuminate\Contracts\Queue\ShouldQueue;<br>use Illuminate\Foundation\Bus\Dispatchable;<br>use Illuminate\Queue\InteractsWithQueue;<br>use Illuminate\Queue\SerializesModels;<br>use Illuminate\Support\Facades\Log;<br><br>class ProcessRabbitMQMessage implements ShouldQueue<br>{<br>    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;<br><br>    /**<br>     * Execute the job.<br>     *<br>     * @return void<br>     */<br>    public function handle()<br>    {<br>        Log::info(&#39;Processing RabbitMQ message!&#39;);<br>    }<br>}</pre><h3>Dispatch job in controller</h3><p>We can dispatch the job that we just created directly in the “web.php” file, but I’d like to dispatch in a separate controller, so let’s create one and make it just invokable:</p><pre>$ php artisan make:controller RabbitMQController --invokable</pre><p>Let’s fill in the following code:</p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use App\Http\Controllers\Controller;<br>use App\Jobs\ProcessRabbitMQMessage;<br><br>class RabbitMQController extends Controller{<br>  public function __invoke()<br>  {<br>    ProcessRabbitMQMessage::dispatch();<br>  }<br>}</pre><p>Nice, and in the final step, let’s add a route for dispatch action:</p><pre>&lt;?php<br>// routes/web.php<br>use App\Http\Controllers\RabbitMQController;<br><br>Route::get(&#39;/process-mq&#39;, RabbitMQController::class);<br></pre><h3>Run queue command</h3><p>In the final step, let’s start processing all RabbitMQ job messages by using the following command:</p><pre>$ php artisan queue:work rabbitmq</pre><h3>Conclusion</h3><p>Remember that all the data you send from your jobs will go to the RabbitMQ server, where you can do whatever you want with this data, but simultaneously, you can process everything in your application.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44f74479062a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-and-rabbitmq-quick-setup-for-processing-queues-44f74479062a">Laravel and RabbitMQ — Quick setup for processing queues</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lit.js + Vite.js — Quick setup and example]]></title>
            <link>https://blog.stackademic.com/lit-js-vite-js-quick-setup-and-example-983ebc9d3652?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/983ebc9d3652</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[lit]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 08:02:34 GMT</pubDate>
            <atom:updated>2024-03-28T00:20:48.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lit.js + Vite.js — Quick Setup and Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Rcg2Bd7HncZhIW4DtPL4g.png" /></figure><p>It’s time to begin my showcase of cool front-end frameworks or libraries/tools — and today we are going to talk about Lit.js, and how you can use this library to build fast web components for your application. Don’t waste time — begin coding 🙌</p><h3>Very quick installation</h3><p>With Vite.js you don’t need to waste your time — just type a few commands, and here you go — a new application with the front-end framework/library that you want will be created. So, go to the terminal and type the following command:</p><pre>$ npm create vite@latest</pre><p>First, type the name of your project (folder name):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC7RkiwFv4-XqPFA0_T0LQ.png" /></figure><p>In the second step, you should select here Lit.js:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ct5zHztvdaKznEcDdFbLNQ.png" /></figure><p>If you want you can use TypeScript in your project, in my case I’m going to use just vanilla JavaScript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBbvn03V6hHVA8Al8FWW4Q.png" /></figure><p>Boom! 💣💥💥💥 That’s all, you will see the latest command that you need to run to install all dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lmt0EyoKEB2que_s1DaXA.png" /></figure><p>When you finish these steps, you can start building your application with Lit.js components ✌️😎</p><h3>Begging example</h3><p>Remember, to run the local server of the app, run the following command:</p><pre>$ npm run dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUT6nUdKNwVOosRjnq5-DA.png" /><figcaption>The message that you will see when you run a local server of the app</figcaption></figure><p>Now go to the following address that you will see in the terminal, and you will see the page generated by default:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKMYacMpUOQVYv1Iy4VXBw.png" /></figure><p>Time to start building a simple example to learn more about Lit.js🙌</p><p>Create a new file named “about.js” inside the “src” folder:</p><pre>import { html, css, LitElement } from &#39;lit&#39;;<br><br>export class About extends LitElement {<br>    // The way how you can define some dynamic CSS styles<br>    static styles = css`p { color: blue }`;<br><br>    // Define props of component<br>    static properties = {<br>        caption: {<br>            type: String,<br>        }<br>    };<br><br>    // Init component - here we can call functions that will be executed before component will be rendered<br>    constructor() {<br>        super();<br>        this.caption = &#39;Default value of caption&#39;;<br>    }<br><br>    // And template of the component<br>    render() {<br>        return html`&lt;p&gt;About us: ${this.caption}&lt;/p&gt;`;<br>    }<br>}<br>customElements.define(&#39;about-card&#39;, About);</pre><p>Nice, time to render this component inside the “my-element.js” file:</p><pre>import { LitElement, css, html } from &#39;lit&#39;<br>import { About } from &#39;./about&#39;<br><br>export class MyElement extends LitElement {<br>  static get properties() {<br>    return {<br><br>    }<br>  }<br><br>  constructor() {<br>    super()<br>  }<br><br>  render() {<br>    return html`<br>       &lt;div class=&quot;main__div&quot;&gt;<br>        &lt;about-card&gt;&lt;/about-card&gt;<br>      &lt;/div&gt;<br>    `<br>  }<br><br>  // If you need to write a custom CSS styles that will work<br>  // with your props in the component, just use styles() function<br>  static get styles() {<br>    return css`<br>      .main__div {<br>        background-color: #fafafa;<br>      }<br>    `<br>  }<br>}<br><br>window.customElements.define(&#39;my-element&#39;, MyElement)</pre><p>Pretty simple to use if you already have experience in front-end frameworks like Vue, React, or Angular, let’s final result on the local server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUooCVEEearYKiq4I7OJUw.png" /></figure><p>It’s working 😎 Before I explain how it works with the index.html file, let’s change the default caption of the “about-card” component:</p><pre>// my-element.js<br>import { LitElement, css, html } from &#39;lit&#39;<br>import { About } from &#39;./about&#39;<br><br>export class MyElement extends LitElement {<br>  static get properties() {<br>    return {<br><br>    }<br>  }<br><br>  constructor() {<br>    super()<br>  }<br><br>  render() {<br>    return html`<br>      &lt;div class=&quot;main__div&quot;&gt;<br>        &lt;about-card caption=&quot;New caption value by using props&quot;&gt;&lt;/about-card&gt;<br>      &lt;/div&gt;<br>    `<br>  }<br><br>  static get styles() {<br>    return css`<br>      .main__div {<br>        background-color: #fafafa;<br>      }<br>    `<br>  }<br>}<br><br>window.customElements.define(&#39;my-element&#39;, MyElement);</pre><p>You should see that the caption is changed on the local server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*mMFmoiNbyDLs7FnVmP5w6Q.png" /></figure><p>That’s the way how you can use props in Lit components to provide some data inside components — it’s just like variables, but created only inside a component (or better to say Lit element).</p><h3>Index.html — how it works?</h3><p>Open the “index.html” — and you already will see that we are rendering the “my-element” component:</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; type=&quot;image/svg+xml&quot; href=&quot;/vite.svg&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Vite + Lit&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;./src/index.css&quot; /&gt;<br>    &lt;script type=&quot;module&quot; src=&quot;/src/my-element.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;my-element&gt;<br>      &lt;h1&gt;Vite + Lit&lt;/h1&gt;<br>    &lt;/my-element&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Pay attention</strong>, that we imported “my-element” just a js file and inserted it like an HTML tag — and that’s all that we need to do, cause all other stuff is compiled automatically by Vite.js. And whenever you save your js/css files in your Lit.js app — Vite automatically refreshes the local server.</p><p>If you need you can change the my-element component inside index.html, and you use the component which you like — you can also include a few components, but it depends on you.</p><h3>Conclusion</h3><p>Boom! Time for conclusion, so it was a short review of using Lit.js and Vite.js together, and as you can see it’s really simple. More about lit.js you can learn from the <a href="https://lit.dev/">official documentation</a>.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983ebc9d3652" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/lit-js-vite-js-quick-setup-and-example-983ebc9d3652">Lit.js + Vite.js — Quick setup and example</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel & Livewire — Quick Setup Guide for Beginners 2024]]></title>
            <link>https://blog.stackademic.com/laravel-livewire-quick-setup-guide-for-beginners-2024-ee8531ceda09?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8531ceda09</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[livewire]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 08:01:59 GMT</pubDate>
            <atom:updated>2024-01-30T03:07:50.932Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel &amp; Livewire — Quick Setup Guide for Beginners 2024</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFC6_8rpxDgoyeuwJ56HDg.png" /></figure><p>Welcome back, in this tutorial, we will learn the basics of the Livewire full-stack framework for Laravel. For those who don’t know what Livewire is, this is a nice toolset for creating a component-based interface for your application with Blade templates and Alpin.js. More features you will see in this article, but before we gonna start creating something — we need to see all the features of Livewire.</p><h3>Livewire features</h3><p>Below I described in my own words the most important features of this framework:</p><ul><li><strong>No special JS framework required</strong>: Don’t want to use Vue to build a reactive interface for your app? No problem, cause with Livewire it’s really easy to build your interface with your components and reactivity without any js-framework.</li><li><strong>Component-based</strong>: Do you need to have reusable components or a component-based interface with your backend for each component? Easy, with Livewire you can create your components that can have their backend code (for example to fetch some data/variables/state) and can be easily rendered without refresh on the client part.</li><li><strong>Easy state changing</strong>: Do you need to use some JS for your UI to make some dynamic behavior? Alpine.js — micro JS framework can help you with that, for example, if you need to make an easy modal system on your page — just add some variables for that in your component and use a few lines of code from Alpine to do that.</li></ul><h3>Installation</h3><p>First of all, let’s create a new Laravel app:</p><pre>$ composer create-project laravel/laravel livewire-tutorial</pre><p>The installation process of Livewire is pretty simple before we are going to make changes in the root template file — we need to install the following dependency:</p><pre>$ composer require livewire/livewire</pre><p>Okay, and now let’s rename the “welcome.blade.php‘ file to “app.blade.php” and put the following code inside:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;{{ str_replace(&#39;_&#39;, &#39;-&#39;, app()-&gt;getLocale()) }}&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;utf-8&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>        &lt;title&gt;Laravel&lt;/title&gt;<br><br>        @livewireStyles<br>    &lt;/head&gt;<br>    &lt;body class=&quot;antialiased&quot;&gt;<br>        &lt;!-- We are going to put here custom layout --&gt;<br>        @livewireScripts<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Great 🙌 We prepared our app for development, it’s time to create some first components.</p><h3>Create layout</h3><p>The first component that we are going to create — will layout of our app, so create a new folder inside the “resources” folder named “components/layouts” and inside this folder create the file “default.blade.php”:</p><pre>&lt;main&gt;<br>    @livewireStyles<br>    &lt;header&gt;<br>        &lt;h2&gt;Header&lt;/h2&gt;<br>    &lt;/header&gt;<br>    {{ $slot }} &lt;!-- Here will go all content of pages that we are going to render --&gt;<br>    @livewireScripts<br>&lt;/main&gt;</pre><p>And let’s go back to the “app.blade.php” and include this layout in this template:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;{{ str_replace(&#39;_&#39;, &#39;-&#39;, app()-&gt;getLocale()) }}&quot;&gt;<br>    &lt;head&gt;<br>        &lt;meta charset=&quot;utf-8&quot;&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>        &lt;title&gt;Laravel&lt;/title&gt;<br><br>        @livewireStyles<br>    &lt;/head&gt;<br>    &lt;body class=&quot;antialiased&quot;&gt;<br>        &lt;x-layouts.default&gt;&lt;/x-layouts.app&gt;<br><br>        @livewireScripts<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now to test it, we need to create a new controller and try to render some simple view templates that we are going to create soon:</p><pre>$ php artisan make:controller HomeController</pre><p>Okay, let’s now create inside this controller the “index” function which will render the “home.blade.php” file that we are going to create in the “views” folder:</p><pre>&lt;?php<br><br>// app/Http/Controllers/HomeController.php<br>namespace App\Http\Controllers;<br><br><br>class HomeController extends Controller<br>{<br>    public function index()<br>    {<br>        return view(&#39;home&#39;); // Nothing special, just default function to render blade templates<br>    }<br>}</pre><p>Don’t forget to create the “home.blade.php” file and put the following code:</p><pre>&lt;x-layouts.default&gt;<br>    &lt;!--<br>      Here we are using x-layouts to use the &quot;default.blade.php&quot;<br>      layout that we created, after typing a dot we type name of layout<br>      that we want to use in this template<br>    --&gt;<br>    &lt;h1&gt;This is homepage&lt;/h1&gt;<br>&lt;/x-layouts.default&gt;</pre><p>Amazing, and finally, let’s add a new route to the “web.php” file to see the final result:</p><pre>&lt;?php<br><br>use App\Http\Controllers\HomeController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/&#39;, [HomeController::class, &#39;index&#39;]);</pre><p>Run the local server and open the homepage of the app, you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhTLA7AkMaHetXjaTkGnbw.png" /></figure><p>Boom 🔥 Layout is working and you just learned how to use Livewire layouts in Laravel apps. Now it’s time to move on to something more complex and interesting.</p><h3>Component creation</h3><p>It’s time to talk about Livewire components and how we can create and use them in the templates, so first, let’s generate a new component by using the following command:</p><pre>$ php artisan make:livewire CreateProduct</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Botkl89zF9f-U0AUQ08ZPQ.png" /><figcaption>Message of success component creation</figcaption></figure><p>First, let’s open the class of this component named “CreateProduct.php” and what we have here:</p><pre>&lt;?php<br><br>namespace App\Livewire;<br><br>use Livewire\Component;<br><br>class CreateProduct extends Component<br>{<br>    public function render()<br>    {<br>        return view(&#39;livewire.create-product&#39;);<br>    }<br>}</pre><p>This is a special Livewire component class where you define all variables, functions, and actions of this component and all this stuff you can easily use in the template. Now let’s see what we have in view file “livewire/create-product.blade.php”:</p><pre>&lt;div&gt;<br>    {{-- The whole world belongs to you. --}}<br>&lt;/div&gt;</pre><p>Nothing special, here you write all template code. So, now let’s back to the component PHP class and create component variables:</p><pre>&lt;?php<br><br>namespace App\Livewire;<br><br>use Livewire\Component;<br><br>class CreateProduct extends Component<br>{<br>    public $title = &#39;Default title value&#39;;<br><br>    public $description = &#39;Default description value&#39;;<br><br>    public $price = 0;<br><br>    public function render()<br>    {<br>        return view(&#39;livewire.create-product&#39;);<br>    }<br><br>    /**<br>     * Save form function<br>     */<br>    public function save()<br>    {<br>        // Let&#39;s try to debug variables values<br>        dd( [ $this-&gt;title, $this-&gt;description, $this-&gt;price ] );<br>    }<br>}</pre><p>We are going to create a form to create products in our application, so let’s imagine that we have variables in the form that we set up above, and now let’s open again component template and write the following code for the form:</p><pre>&lt;div&gt;<br>    &lt;form wire:submit=&quot;save&quot;&gt; &lt;!-- Here we define that save() function that we just created will be called when user will submit a form  --&gt;<br>        &lt;div class=&quot;form__field&quot;&gt;<br>            &lt;label&gt;Title&lt;/label&gt;<br>            &lt;input type=&quot;text&quot; wire:model=&quot;title&quot; /&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form__field&quot;&gt;<br>            &lt;label&gt;Description&lt;/label&gt;<br>            &lt;textarea wire:model=&quot;description&quot;&gt;&lt;/textarea&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;form__field&quot;&gt;<br>            &lt;label&gt;Price&lt;/label&gt;<br>            &lt;input type=&quot;number&quot; wire:model=&quot;price&quot; /&gt; &lt;!-- By using wire:model we choose which variable will changed by changing input --&gt;<br>        &lt;/div&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Create product&quot; /&gt;<br>    &lt;/form&gt;<br>&lt;/div&gt;</pre><p>Amazing, now let’s show this component on the “home.blade.php”:</p><pre>&lt;x-layouts.default&gt;<br>    &lt;h1&gt;This is homepage&lt;/h1&gt;<br>    &lt;livewire:create-product /&gt;<br>    &lt;!--<br>      After typing livewire: we type name of<br>      component that we want to render<br>    --&gt;<br>&lt;/x-layouts.default&gt;</pre><p>Time to test it! Let’s see what we got in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iB_Xmb87Wvf7aGXn4HxBQg.png" /></figure><p>Try to update the values of inputs and submit a form, and you should see debug:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLgm1X4MMmobqOP1vO9Uyw.png" /></figure><p>Looks fine, just for you to know — inside the “save()” function you can easily write all code to work with this data, and as you can see you don’t to write any special JS code for this, just use Livewire to make reactive UI.</p><h3>More about events, features</h3><p>So, cause this article is a really short quick guide — I can’t show you all the features of Livewire. But, Livewire has great <a href="https://livewire.laravel.com/docs/quickstart">documentation</a> that you can check:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9Ek0sXaHmLXwrO5e77h9A.png" /><figcaption>Livewire documentation is simple and here you can find all the answers</figcaption></figure><h3>Conclusion</h3><p>It’s really simple to start using Livewire and you can see that it’s really easy to use — cause you don’t need to write any JS code, you just write all the backend logic of components in PHP files and create components templates with Livewire markup.</p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8531ceda09" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/laravel-livewire-quick-setup-guide-for-beginners-2024-ee8531ceda09">Laravel &amp; Livewire — Quick Setup Guide for Beginners 2024</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enums and Laravel — small development tips]]></title>
            <link>https://blog.stackademic.com/enums-and-laravel-small-development-tips-f26c9439e173?source=rss-152f864614c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26c9439e173</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Demian Kostelny]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 08:02:37 GMT</pubDate>
            <atom:updated>2024-01-22T01:42:22.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enums and Laravel — small development tips</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EidyrZyUINClQYIXZTkxYA.png" /></figure><p>Boom 🔥 Greetings to everyone, and in this short article I’m going to show you everything that you need to know to start using enums in your laravel projects. Yeah, this is one of the small tips that will help you to write clean code and make more clear architecture, so let’s begin buddy 😎</p><h3>What is enum?</h3><p>Okay, you reading this article and you don’t know what is enum in PHP? No problem, let me explain. Imagine that you have a User model and in your application, you have user roles, so the user role is saved in that User model in the field named “role” — which can accept string type. For example, if the user has an admin role, that means that the “role” field has the value “admin” — just a string value.</p><p>And you want to save the list of all available roles for users somewhere in class or something like that — not in the database. In this case, you will be using Enums, a new feature in PHP 8. In short, we can describe enums as a class that saves values of possible cases — sounds strange, but soon you will understand how it simple is to use.</p><h3>Enum syntax</h3><p>First of all, let’s move on to the empty Laravel app, we will need to create an empty folder named “Enums” in the “app” folder, and after that let’s create a new file named “Role.php”:</p><pre>&lt;?php<br><br>namespace App\Enums;<br><br>// Below we declare enum and data type that will return this enum (optional)<br>enum Role: string<br>{<br>  // Now we can define all possible cases for role field<br>  case ADMIN = &#39;admin&#39;;<br><br>  case MODERATOR = &#39;moderator&#39;;<br><br>  case EDITOR = &#39;editor&#39;;<br><br>  case CUSTOMER = &#39;customer;<br>}<br></pre><p>Great, we created our first enum, it’s time to use it in user migration, but don’t forget also to run the following composer command:</p><pre>$ composer dump-autoload</pre><h3>Use enums in migrations</h3><p>Let’s define the default value of the user’s role in the user&#39;s migration file:</p><pre>&lt;?php<br><br>use App\Enums\Role;<br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>return new class extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     */<br>    public function up(): void<br>    {<br>        Schema::create(&#39;users&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;string(&#39;role&#39;)-&gt;default(Role::EDITOR-&gt;value); // This is the way how can you ad<br>            $table-&gt;string(&#39;email&#39;)-&gt;unique();<br>            $table-&gt;timestamp(&#39;email_verified_at&#39;)-&gt;nullable();<br>            $table-&gt;string(&#39;password&#39;);<br>            $table-&gt;rememberToken();<br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     */<br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;users&#39;);<br>    }<br>};</pre><p>Now by default, every user will have an “editor” role, and pay attention that we are using the arrow to get the value of the case that we want to use.</p><h3>User model</h3><p>Let’s also make some changes to the User model:</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>use App\Enums\Role;<br>use Illuminate\Database\Eloquent\Factories\HasFactory;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br>use Laravel\Sanctum\HasApiTokens;<br><br>class User extends Authenticatable<br>{<br>    use HasApiTokens, HasFactory, Notifiable;<br><br>    /**<br>     * @var array&lt;int, string&gt;<br>     */<br>    protected $fillable = [<br>        &#39;name&#39;,<br>        &#39;email&#39;,<br>        &#39;password&#39;,<br>    ];<br><br>    /**<br>     * @var array&lt;int, string&gt;<br>     */<br>    protected $hidden = [<br>        &#39;password&#39;,<br>        &#39;remember_token&#39;,<br>    ];<br><br>    /**<br>     * @var array&lt;string, string&gt;<br>     */<br>    protected $casts = [<br>        &#39;email_verified_at&#39; =&gt; &#39;datetime&#39;,<br>        &#39;password&#39; =&gt; &#39;hashed&#39;,<br>        &#39;role&#39; =&gt; Role::class, // Define that role field can only get values from the Role enum<br>    ];<br>}</pre><h3>Conclusion</h3><p>Yeah, as you can it’s so easy to use enums in your models and migrations to define possible cases for some table field. It’s easy and this makes your code more clean and better. Boom 🔥 Let’s see other developer tips in the next articles.</p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26c9439e173" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/enums-and-laravel-small-development-tips-f26c9439e173">Enums and Laravel — small development tips</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>