<?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 Agri Kridanto on Medium]]></title>
        <description><![CDATA[Stories by Agri Kridanto on Medium]]></description>
        <link>https://medium.com/@agri.kridanto?source=rss-a22faaf19fb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ChD8f6MIi3obhIhYnVydXA.jpeg</url>
            <title>Stories by Agri Kridanto on Medium</title>
            <link>https://medium.com/@agri.kridanto?source=rss-a22faaf19fb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:04:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agri.kridanto/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[Transcribe and Translate Audio/Voice Data with Whisper API]]></title>
            <link>https://medium.com/@agri.kridanto/transcribe-and-translate-audio-voice-data-with-whisper-api-7b002f9672d8?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b002f9672d8</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[whisper]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 05:54:09 GMT</pubDate>
            <atom:updated>2023-03-25T21:33:18.538Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, how’s your day ?? I hope y’all are doing well on your end. It’s been a while since my last post about <a href="https://medium.com/@agri.kridanto/how-to-generate-ai-images-using-dall-e-and-telegrambot-in-laravel-free-trial-inside-7dda6a5f8945">Generating AI Images with Telegram Bot </a>. Today, I want to share about using Whisper API to transcribe and translate your audio/voice data. Like my previous posts, for chatbot implementation and generating AI Images, I’ll be using OpenAI API for this one as well. I’m also mentioned how to implement this Whisper API for my Telegram ChatBot.</p><p>On 1st March 2023, <a href="https://openai.com/blog/introducing-chatgpt-and-whisper-apis">OpenAI launches their Whisper API </a>, as well as the ChatGpt API (with gpt 3.5 turbo model). Whisper is a service that we can use to transcribe (and translate) our audio data into text-based, or so-called speech-to-text model.</p><blockquote>ChatGPT and Whisper models are now available on our API, giving developers access to cutting-edge language (not just chat!) and speech-to-text capabilities. Through a series of system-wide optimizations, we’ve achieved 90% cost reduction for ChatGPT since December; we’re now passing through those savings to API users. Developers can now use our open-source Whisper large-v2 model in the API with much faster and cost-effective results. ChatGPT API users can expect continuous model improvements and the option to choose dedicated capacity for deeper control over the models. We’ve also listened closely to feedback from our developers and refined our API terms of service to better meet their needs. — <strong>OpenAI on launching Whisper and ChatGPT</strong></blockquote><p>The ChatGPT API is more or less the same as GPT-3 model, with very cost-effective token usage, only 10% compared with the daVinci model. If you ever using my chatbot, it had been implemented gpt-3.5-turbo (which powered ChatGPT), I implement that with minor changes to the code (from GPT-3 model to gpt-3.5-turbo).</p><blockquote>Whisper is an automatic speech recognition (ASR) system trained on 680,000 hours of multilingual and multitask supervised data collected from the web. We show that the use of such a large and diverse dataset leads to improved robustness to accents, background noise and technical language. Moreover, it enables transcription in multiple languages, as well as translation from those languages into English. We are open-sourcing models and inference code to serve as a foundation for building useful applications and for further research on robust speech processing. — <a href="https://openai.com/research/whisper">Introducing Whisper (openai.com)</a></blockquote><p>This blog will focus on accessing Whisper API to transcribe and translate our audio/voice data. The endpoint will accept audio formats such as mp3, mp4, mpeg, mpga, m4a, wav, and webm. The maximum of file size uploaded to the endpoint is limited to <strong>25 MB</strong>.</p><p>The transcriptions API takes as input the audio file you want to transcribe and the desired output file format for the transcription of the audio. We can expect text or <em>srt </em>format. The <em>srt</em> format would be very useful if you want to make subtitles on your video content. The supported languages are described in <a href="https://platform.openai.com/docs/guides/speech-to-text/supported-languages">Whisper page</a> and Indonesian is one of supported languages by Whisper !!</p><p>Meanwhile, the translate API endpoint will take your audio file and <strong>translate to English text</strong>. I hope the model will support translation to other languages as well in the future.</p><p>Let’s move to implementation. I’m still using the Laravel OpenAI package to implement the translation and transcription of Whisper. Thanks to the package, the implementation is very handy.</p><p><a href="https://github.com/openai-php/laravel">GitHub - openai-php/laravel: ⚡️ OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with OpenAI API</a></p><p>This is the code implementation for transcribe endpoint. This function accepts the parameter filename from the audio file which previously stored on our storage. <strong>On line 11</strong>, we can specify which output we are expecting for the transcribe endpoint, we can use an <em>srt</em>, text, or verbose-json as our needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmbtJTXHjJa3pz0_KRjUJg.png" /><figcaption>Code snippet to access whisper transcribe &amp; translation endpoint from Laravel</figcaption></figure><p>I only differentiate which endpoint I want to access based on parameters <em>$type</em>. Meaning, it will access the <strong>transcribe endpoint</strong> and return the expected format of text; Or <strong>translate the endpoint</strong> and return English text based on my requirements. I hope the explanation is quite easy to understand.</p><p>Enough for the coding part, these are the example of output from transcribe endpoint. The result is superb, it was the same with the subtitles written from the sources. I got the audio (.mp3) file from this link :</p><p><a href="https://commons.wikimedia.org/wiki/File:Roosevelt_Infamy.ogg">File:Roosevelt Infamy.ogg — Wikimedia Commons</a></p><blockquote>Yesterday, December 7, 1941, a date which will live in infamy, the United States of America was suddenly and deliberately attacked by naval and air forces of the Empire of Japan. — Whisper output on Roosevelt Infamy.ogg</blockquote><p>The second sample, when I uploaded the Indonesian Proclamation Independence By Ir. Soekarno, First President of Indonesia. I think it’s quite amazing the output text is both in transcribing and translating, I think, I just need to add minor fixing to the output.</p><blockquote>Proklamasi kami bangsa Indonesia dengan ini menyatakan kemerdekaan Indonesia hal-hal yang mengenai pemindahan kekuasaan dan lain-lain diselenggarakan dengan cara saksama dan dalam tempo yang sesingkat-singkatnya Jakarta 17 Agustus 1945 atas nama bangsa Indonesia Soekarno-Hatta — <strong>Whisper API output on trancribing audio file on Indonesian Proclamation Independence</strong>.</blockquote><blockquote>Indonesia’s Independence Proclamation We, the people of Indonesia, hereby declare Indonesia’s independence. All matters concerning the transfer of power and others are to be discussed in an equal manner and in the shortest possible time. Jakarta, 17th August 1945, on behalf of the Indonesian nation, Soekarno-Hatta. Indonesia’s Independence Proclamation — <strong>Whisper API output on translate audio file on Indonesian Proclamation Independence</strong>.</blockquote><p>I’m also try the <em>srt </em>format from the youtube video about Ir Soekarno’s speech on Indonesian Proclamation Independence, taken from this link :</p><p><a href="https://www.youtube.com/watch?v=4v8I-DuubqE">(97) pidato bung karno kemerdekaan indonesia 17 agustus 1945 *proklamasi* — YouTube</a></p><p>And the result is very amazing. Sorry, I print it in the console so it might differ with the exact <em>srt </em>format. But, I think you got my point, this transcribe endpoint and <em>srt</em> output would be very useful to make subtitles / captions of video content. If you have such kind of works to make subtitles for your video contents, <strong>You should try it</strong>.</p><pre>1<br>00:00:00,000 --&gt; 00:00:15,000<br>Saudara-saudara sekalian, saya telah minta saudara-saudara hadir di sini untuk menyaksikan satu peristiwa maha penting dalam sejarah kita.<br><br>2<br>00:00:15,000 --&gt; 00:00:23,000<br>Berpuluh-puluh tahun kita bangsa Indonesia telah berjuang untuk kemerdekaan tanah air kita.<br><br>3<br>00:00:23,000 --&gt; 00:00:37,000<br>Maka telah beratus-ratus tahun, gelombang aksi kita untuk mencapai kemerdekaan kita itu ada naiknya dan ada turunnya.<br><br>4<br>00:00:37,000 --&gt; 00:00:41,000<br>Tetapi jiwa kita tetap menuju ke arah cita-cita.<br><br>5<br>00:00:41,000 --&gt; 00:00:51,000<br>Juga di dalam zaman Jepang, usaha kita untuk mencapai kemerdekaan nasional tidak berhenti-henti.<br><br>6<br>00:00:51,000 --&gt; 00:00:58,000<br>Di dalam zaman Jepang ini, tampaknya saja kita menyandarkan diri kepada mereka.<br><br>7<br>00:00:58,000 --&gt; 00:01:07,000<br>Tetapi pada hakikatnya, tetap kita menyusun tenaga kita sendiri. Tetap kita percaya kepada kekuatan sendiri.<br><br>8<br>00:01:07,000 --&gt; 00:01:17,000<br>Sekarang, tibalah saatnya kita benar-benar mengambil nasib bangsa dan nasib tanah air di dalam tangan kita sendiri.<br><br>9<br>00:01:17,000 --&gt; 00:01:26,000<br>Hanya bangsa yang berani mengambil nasib dalam tangan sendiri akan dapat berdiri dengan kuatnya.<br><br>10<br>00:01:26,000 --&gt; 00:01:36,000<br>Maka kami tadi malam telah mengadakan <strong>permusyawaraan </strong>dengan pemuka-pemuka rakyat Indonesia dari seluruh Indonesia.<br><br>11<br>00:01:36,000 --&gt; 00:01:47,000<br>Permusyawaratan itu seiya sekata berpendapat bahwa sekaranglah datang saatnya untuk menyatakan kemerdekaan kita.<br><br>12<br>00:01:47,000 --&gt; 00:01:54,000<br>Saudara-saudara, dengan ini kami nyatakan kebulatan tekat itu.<br><br>13<br>00:01:54,000 --&gt; 00:02:12,000<br>Dengarlah proklamasi kami. Proklamasi kami, bangsa Indonesia, dengan ini menyatakan kemerdekaan Indonesia.<br><br>14<br>00:02:12,000 --&gt; 00:02:29,000<br>Hal-hal yang mengenai pemindahan kekuasaan dan lain-lain diselenggarakan dengan cara saksama dan dalam tempo yang sesingkat-singkatnya.<br><br>15<br>00:02:29,000 --&gt; 00:02:45,000<br>Jakarta, 17 Agustus 1945, atas nama bangsa Indonesia, Sukarno-Hatta.<br><br>16<br>00:02:45,000 --&gt; 00:02:50,000<br>Demikianlah, saudara-saudara, kita sekarang telah <strong>berdeka</strong>.<br><br>17<br>00:02:50,000 --&gt; 00:02:56,000<br>Tidak ada satu ikatan lagi yang mengikat tanah air kita dan bangsa kita.<br><br>18<br>00:02:56,000 --&gt; 00:03:01,000<br>Mulai saat ini, kita menyusun negara kita.<br><br>19<br>00:03:01,000 --&gt; 00:03:08,000<br>Negara merdeka, negara Republik Indonesia. Merdeka kekal dan abadi.<br><br>20<br>00:03:08,000 --&gt; 00:03:27,000<br>Insya Allah, Tuhan memberkati kemerdekaan kita itu.</pre><p>I’m also implementing this Whisper API on my Telegram Chatbot, and it was quite easy to implement. If you do not read my previous article yet, you can access it at this <a href="https://medium.com/@agri.kridanto/integrate-laravel-with-chatgpt-and-telegram-bot-2f0ac5995452">link</a>. There are my notes on implementing in Telegram Bot :</p><ol><li><strong>Telegram voice chat is in .ogg format, so we need to convert it with other services. But when using .mp3 or another file supported by Whisper, we can implement it directly.</strong></li><li>The message sent by Telegram Bot is limited about <strong>4096 </strong>characters. So, if it is longer than 4096 characters, we need to decompose into several messages.</li></ol><p>This is a sample of utilizing whisper in my TelegramBot. The ChatBot receives the audio file in the form of .mp3 file in the Indonesian language which is the summary of <a href="https://angeladuckworth.com/grit-book/">GRIT book by Angela Duckworth</a>. Then, the Laravel Backend accesses Whisper to transcribe and translate it to English.</p><blockquote>This is a message from this book. Talent does not guarantee you achievement. You can have talent without hard work and diligence. But that talent will be not optimal and will not develop. Whereas talent, effort and achievement can be achieved together. Having talent and effort will produce skill. By having talent and effort, you can achieve achievements. Advice from this book. Find out what makes you interested in something. Then enjoy the time doing and trying it. Set a high target, then try to reach it. Work consistently, not only in a day or a month. But for years to come. — GRIT by Angela Duckworth</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*3ExgXqPuWqVGsBcYFZWCrQ.jpeg" /><figcaption>Sample accessing Whisper Translate from Telegram Bot</figcaption></figure><p>Let’s move to whisper’s pricing model. The Whisper API is <strong>$0.006 / minute</strong> both for transcribing and translating audio data as described on <a href="https://openai.com/pricing">OpenAI website</a>. I’ve also captured my token usage to access this service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YNJjMc3_bxxUfu4QPSkiNA.png" /><figcaption>Whisper API pricing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*QG_U_J9H083-cM4-HxoBpA.png" /><figcaption>My Token Usage when accessing Whisper API</figcaption></figure><p>As captured above, I’m also trying about<strong> 20 mins long of audio data (the file size is about 20MB</strong>), and the result is quite good, <strong>but still need extra work to do </strong>like<strong> </strong>adding punctuation and minor fixing on typo words of generated text. The resulting text is about <strong>15K characters</strong>, so I need to breakdown into 4–5 messages when send it with my telegram bot.</p><p>Ok, that’s all from me, we have explored the integration of the Whisper API with Laravel and Telegram Bot. I hope it has provided valuable insights and useful information for you. If you have any questions or ideas, please don’t hesitate to ask. Feel free to follow and share this article.</p><p>Thanks for your time and I look forward to seeing you in the next one. Have a good day !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b002f9672d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Generate AI Images Using DALL-E and TelegramBot in Laravel:  Free Trial Inside]]></title>
            <link>https://medium.com/@agri.kridanto/how-to-generate-ai-images-using-dall-e-and-telegrambot-in-laravel-free-trial-inside-7dda6a5f8945?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dda6a5f8945</guid>
            <category><![CDATA[dall-e-2]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[ai-generated-image]]></category>
            <category><![CDATA[openai-api]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 03:25:23 GMT</pubDate>
            <atom:updated>2023-03-18T09:41:58.445Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Generate AI Images Using DALL-E and TelegramBot in Laravel: Free Trial Inside</h3><p>Hello Everyone, how is your day ? I hope everything is great on your end.</p><p>In this blog, I will continue the Laravel and OpenAI integration with Telegram Bot. I will share additional features on the Telegram Bot to produce images generated by AI, through Dall-E. So that end-users can submit their ideas, and the bot will generate images from their ideas.</p><p>For all of you who haven’t read my articles about OpenAI Integration with Laravel and Telegram Bot, you can access my previous article, <a href="https://medium.com/@agri.kridanto/integrate-laravel-with-chatgpt-and-telegram-bot-2f0ac5995452">Integration of Telegram Bot and Laravel and ChatGPT</a>. At the end of this article, <strong>I will give a free trial bot access for those who want to try it</strong>. Including the workaround of adding context discussion on the chatbot which I explain <a href="https://medium.com/@agri.kridanto/chat-gpt-api-add-memory-and-context-of-discussion-6a18b92bd47a">in this article</a>.</p><p>Dall-E is an AI system owned by OpenAI, to generate images based on the descriptions/commands from users. A more detailed explanation about Dall-E can be accessed at this link.</p><blockquote>DALL·E 2 is a new AI system that can create realistic images and art from a description in natural language. — <a href="https://openai.com/dall-e-2/">DALL·E 2 (openai.com)</a></blockquote><p>Here’s an example of when we use Dall-E on the <a href="https://labs.openai.com/">Labs of Open AI page</a>. That’s awesome, right ? We just convey imagination and these images are generated in seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*huOfaySo1oGB5e1M.png" /><figcaption>Sample usage of Dall E from their Labs <a href="https://labs.openai.com/">page</a></figcaption></figure><p>Like other OpenAI services, such as GPT, Dall E can also be accessed via the API. Therefore, we will use the package as we used on previous articles to access Dall-E through the Laravel framework.</p><p><a href="https://github.com/openai-php/laravel">GitHub - openai-php/laravel: ⚡️ OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with OpenAI API</a></p><p>Actually, Dall-E’s API service is not only for producing images, but can also edit images, and generate image variations. However, in this blog, I’ll only explain how to generate images, because it is more specific for my additional features in Telegram ChatBot. The Dall-E endpoint on the OpenAI API for generating images requires the following parameters:</p><ul><li><em>prompt</em>: command/idea that we give to generate an image (maximum 1000 characters)</li><li><em>n</em>: the number of images generated (between 1 to 10 images)</li><li><em>size</em>: the size of the resulting image (256 x 256, 512 x 512, or 1024 x 1024)</li></ul><p>The clearer <em>prompt </em>we provide, the more specific and detailed the resulting image will be. Meanwhile, <em>n and size</em>, are the options that we can adjust to our needs. Here, I’m using the option <strong>n =1</strong> and <strong>size= 256*256 </strong>. This option allows us to produce images the fastest and at the most competitive cost compared to other options. Of course, I prefer this options based on my requirements. A more complete explanation of the Dall E-API can be accessed via the following link.</p><p><a href="https://platform.openai.com/docs/guides/images/introduction">OpenAI API</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0SWM2p__WX2y6Bvv.png" /><figcaption>Pricing of Dall E services</figcaption></figure><p>What about the output given? The image output provided by Dall-E can be selected in 2 formats, which is :</p><p>— URL: Public URL that we can access directly through the browser. But this URL is only active 1 hour after the response was generated.</p><p>— Base64: We get Base64 format which we can convert to a file.</p><p>From the 2 options above, I use the URL option. If there is a requirement to save the image, we can also easily implement it in Laravel. Thanks to <a href="https://laravel.com/docs/9.x/filesystem">Facades Storage</a>. Following is the code snippet to make a request to OpenAI.</p><pre>public function generateImage($image_request){<br>    $result = OpenAI::images()-&gt;create([<br>        &#39;prompt&#39; =&gt; $image_request,<br>        &#39;n&#39; =&gt; 1,<br>        &#39;size&#39; =&gt; &#39;256x256&#39;,<br>        &#39;response_format&#39; =&gt; &#39;url&#39;,<br>    ]);<br><br>    // save to local if needed.<br>    $file = &#39;base64_&#39;. md5(Carbon::now()-&gt;toDateTimeString());<br>    Storage::disk(&#39;local&#39;)-&gt;put($file.&#39;.png&#39;, file_get_contents($result[&quot;data&quot;][0][&quot;url&quot;]));<br><br>    return $result[&quot;data&quot;][0][&quot;url&quot;];<br>}</pre><p>An example of the response that is generated like the following image where we will retrieve the URL address of the response provided. In the code example above, we save the image in the <em>storage&gt;&gt;app</em> folder in our Laravel project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*ERRWwF8gDDKjzkDH.png" /><figcaption>sample of response on Dall E endpoint</figcaption></figure><p>The code example above allows us to save the image to the server, so we can process it further as needed. However, in this chatbot implementation that uses Telegram, I chose to use the <strong>InputFile </strong>provided by the Telegram Bot package.</p><p><a href="https://telegram-bot-sdk.readme.io/docs/getting-started">Getting Started</a></p><p>The InputFile accepts parameters in the form of a URL (which is the response from the OpenAI API) and filename so that we can form the image on the fly when sending the image to the user. In the code above, I include the image caption according to the prompt / request given by the user.</p><pre>$response = $ai-&gt;generateImage($image_request);<br>$filename = $from-&gt;id.&#39;-&#39;. Carbon::now()-&gt;timestamp .&#39;.jpg&#39;;<br><br>$response = Telegram::sendPhoto([<br>    &#39;chat_id&#39; =&gt; $from-&gt;id, <br>    &#39;photo&#39; =&gt; new InputFile($response, $filename),<br>    &#39;caption&#39; =&gt; $imagine_active-&gt;image_request<br>]); </pre><p>The sample result when we access Dall-E via Telegram is as following figures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*2KA0KGCsZ_0rMMJK.png" /><figcaption>Sample 1 — A Doctor Strange in multiverse of madness riding horse with lightning speed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IM5DelxWBi4gxML.png" /><figcaption>Sample 2— Iron Man bring super armor to fight Thanos in Mars planet</figcaption></figure><p>That’s all, the Dall E feature that I added to my Telegram ChatBot. Of course, you can also use the Dall-E feature as per your requirements. As I said above, I will give <strong>a trial of this bot for 1 day each to 15 people (there is a quota for services provided, both chat and generating images),</strong> I hope you can suggest me to improve this bot further.</p><p>If you are interested, please follow my medium account and comment on this article or <a href="http://t.me/agriirga">DM me on Telegram</a>. I believe that concludes this blog post, and I hope it will provided valuable insights for us. If you have any questions, please don’t hesitate to ask in the comments section.</p><p>Additionally, feel free to follow and share this article. Thanks for your time and attention, see you soon on the next posts. Have a good day !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dda6a5f8945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chat GPT API : Add memory and context of discussion]]></title>
            <link>https://medium.com/@agri.kridanto/chat-gpt-api-add-memory-and-context-of-discussion-6a18b92bd47a?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a18b92bd47a</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[chatgpt-chatbot]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[chatgptapi]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 00:28:11 GMT</pubDate>
            <atom:updated>2023-02-25T11:54:12.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chat GPT API : Add memory and context of discussion</h3><p>Hello Worlds, I hope everything is great on your end. Today, I want to share about the possible solution on how to add memory and context of discussion while we access ChatGPT API.</p><p>In the previous article, I shared <a href="https://medium.com/@agri.kridanto/integrate-laravel-with-chatgpt-and-telegram-bot-2f0ac5995452">the idea of integrating Telegram Bot, Laravel, and ChatGPT</a>. I think this idea can also be implemented for other chatbots and other frameworks, not only Telegram Bot and the Laravel Framework. However, when developing the bot prototype, I encountered a significant issue, this ChatBot did not recognize the context of the conversation between the user and itself, which was quite unsettling. <strong>The solution I proposed here is a <em>workaround </em>and has high-cost consequences when accessing the API</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*wdPDQnAmluiWQayD.png" /><figcaption>Sample 1 — Discussion on World War 3</figcaption></figure><p>The picture above is one of the snippets of my discussion with bots about World War 3. Take a look at the text in a red box. <em>“Based on your learning, is there any person or institution that will predict that?” </em>But the bot doesn’t recognize the context of the conversation and instead answers about the <strong>stock market</strong>, LOL.</p><p>After I replied, <em>“No, I don’t talk about the stock market. About the World War 3”.</em> He returned to the topic of World War 3, but still, he did not recognize the context of my question about the person or institution that predicted World War 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*S2PQ7SFBLBOl0NZy.png" /><figcaption>Sample 2, Discussion about Covid-19</figcaption></figure><p>Another example is when we talk about Covid-19. In the first picture above, I asked the ChatBot to name the total suspects in Covid-19. (Previously he gave a list of 10 countries with the most incidents). <em>Sorry, it shouldn’t be suspect. My bad.</em></p><p>Back to my discussion with the ChatBot. <em>“How about Indonesia?”</em> He explained the description of Indonesia. Very good explanation about my country. <strong>But, out of context</strong>.</p><blockquote><strong>Indonesia is the world’s fourth most populous country, with over 270 million people. It is a diverse nation with more than 700 languages spoken, and is home to some of the world’s most beautiful beaches, jungles, and volcanoes. Indonesia is also a major economic power in Southeast Asia, with a large and growing middle class. — ChatGPT describe Indonesia</strong></blockquote><p>It looks like, this problem was also discussed on the StackOverflow forum, here is one of discussion about it : <a href="https://stackoverflow.com/questions/74711107/openai-api-continuing-conversation">python — Openai API continuing conversation — Stack Overflow</a>. The solution that is quite helpful from user <a href="https://stackoverflow.com/users/5242363/special1st">Special1st</a> described in picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ljOy8u_6HxtY5j4t.png" /><figcaption>possible solution on how to add contex of discussion on openAI API</figcaption></figure><p>The idea is that <strong>we include the questions and answers from the previous talk</strong>, so that the OpenAI API understands the context that we are talking about. I’m trying to implement the solution on a ChatBot that I’ve developed.</p><p>Here’s the pseudocode:</p><ol><li>Users make requests (Question/<strong>Q</strong>) and Open AI provides answers (Answer/<strong>A</strong>) via the API .</li><li>Save the <strong>Q&amp;A pairs</strong> into the database and <strong>include the timestamp</strong>.</li><li>Every time there is <strong>a new request/query from the user, get the Q &amp; A pairs from step 2</strong>.</li><li><strong>Limit the number of records</strong> (eg 3 records) and sort them in <strong>descending </strong>order.</li><li>Setup prompt when Request to Open AI API with data we have collected in step 4 .</li><li>Repeat number 1</li></ol><p>The following is the table structure that I’ve implemented in the MySQL database to store conversation records between users and openAI via Telegram Bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*3iDd_b_EPDUHd4g2.png" /><figcaption>table structure to store user and ChatBot conversation</figcaption></figure><p>I hope it’s clear enough for the pseudocode and the usage of the table above. Here’s a snippet of my code implementation in PHP. In below code, I store <strong>Q&amp;A records in the tGptChatResponse</strong> Model to access the table we have set up to store the <strong>Q&amp;A</strong> records (Line 7). Next, I iterate the records to construct the prompt (the <em>$context</em> variable) before I access the OpenAI API on Line 13.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4D_Beidk6pDPfLdX.png" /><figcaption>Snippet code to implement the solution above</figcaption></figure><p>After We tried implementing the code, ChatBot understood the context of our conversation, even though it was only limited to the last 3 conversations (according to the code above, <strong>Line 3</strong>). The following is an examples of our discussion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*nD4tjV8jlBTooDkYH5l3UA.png" /><figcaption>Sample Result, discussion about Ir Soekarno, first president of Indonesia</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*fl-SSkv65rP51Adk.png" /><figcaption>Sample Result, discussion about Switzerland</figcaption></figure><p>Just a little intermezzo, there’s something weird about the last answer above when discussing about Switzerland. <em>“That is great from you. How do you know history?</em> Here’s the answer. LOL.</p><blockquote>I have studied the history of Switzerland extensively, <strong>both in school and on my own</strong>. I have read books, <strong>visited museums, and spoken to people who have lived in the country for many years</strong>. I also keep up to date with current events in Switzerland, which helps me to understand the country’s history and culture. — CHATGPT ‘S ANSWER ON LEARNING HISTORY ABOUT SWITZERLAND</blockquote><p>But never mind, we must be aware that chatGPT <strong>can help us, but of course it also has many drawbacks</strong> 🙂. <strong>Please, do not depend too much on this thing !!</strong></p><p>Talking about the drawbacks, back to the solution we’ve proposed, we can see that the ChatBot can understand the context of the conversation. <strong>However, this solution is very expensive</strong>, because it is related to the token that we use when accessing the service. Below is a screenshot of my Token Usage when using the ‘solution’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GXg3C6sTaGLvIYPZ.png" /><figcaption>sample of Usage of Tokens <strong>after </strong>implementing this solution</figcaption></figure><p>We can see access to the API service, the <em>prompt </em>is the request we <strong><em>send </em></strong>to OpenAI API, while the <em>completion </em>is the response <strong><em>from </em></strong>the openAI API. The prompt that we give is almost 4 times of the completion. <strong>The total tokens used reached 1628 tokens</strong>.</p><p>As a comparison, here’s an example of using tokens <strong>before </strong>I implemented the ‘solution’ above. The prompt that we use, is according to the request written by the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FVOywW7VVoFZW_Cf.png" /><figcaption>sample of usage token before <strong>implement </strong>this solution</figcaption></figure><p>The comparison is quite stark at access prompts because <strong>the solution above includes a pair of Q&amp;A on subsequent requests</strong>. And it must be remembered, there is a max token limit when we make requests to the OpenAI API service, for example, <strong>text-davinci-003 has a maximum limit of 4000 tokens for each request</strong>. Other models, <strong>text-curie-001, text-babbage-001, and text-ada-001 has 2048 token max </strong>in each request. Therefore, I’m only including the last 3 conversations on the solution above.</p><p>As an additional reference, you can access the pricing model and usage of tokens on the following page: <a href="https://platform.openai.com/docs/models/gpt-3">Models — OpenAI API</a> and <a href="https://openai.com/api/pricing/">Pricing (openai.com)</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J1HciqIxQbV6hyD-.png" /><figcaption>Max Request for each GPT-3 Model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RwVx0ZaN4KBEBGPR.png" /><figcaption>Pricing of base models</figcaption></figure><p>For example, if we use the DaVinci Model (text-davinci-003) <strong>we are limited to 4000 tokens when requesting the openAI service</strong>, and <strong>the price per 1000 tokens (about 750 words) is USD 0.02</strong>.</p><p>I think that’s enough from me. I hope this article can provide benefits and insight for us. Please follow me on Medium and share this post if you feel this article is helpful<strong>. If you have better or optimal solution of this problem, please kindly to share it :).</strong></p><p>Any questions or ideas ? You can also write in the comments section or contact me via <a href="https://www.linkedin.com/in/agri-kridanto-03890484/">LinkedIn</a>. Thanks for your time and I’ll see you in the next posts. Have a nice day !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a18b92bd47a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Laravel with ChatGPT and Telegram Bot]]></title>
            <link>https://medium.com/@agri.kridanto/integrate-laravel-with-chatgpt-and-telegram-bot-2f0ac5995452?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f0ac5995452</guid>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 09:06:34 GMT</pubDate>
            <atom:updated>2023-03-25T09:57:22.160Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Worlds, I want to share about the idea to integrate chatGPT with Telegram Bot, and of course with the Laravel Framework. In the last month, there has been a lot of excitement about ChatGPT, a chat-based AI services developed by OpenAI. The AI system which we can communicate in a conversational way.</p><p><strong>Updated on 25/03/2023</strong> : I have add some features on my chatbot as mentioned in my other post. <br>1. <a href="https://medium.com/@agri.kridanto/chat-gpt-api-add-memory-and-context-of-discussion-6a18b92bd47a">ChatGPT API : Add memory and context of discussion</a> <br>2. <a href="https://medium.com/@agri.kridanto/how-to-generate-ai-images-using-dall-e-and-telegrambot-in-laravel-free-trial-inside-7dda6a5f8945">Generating AI Images using Dall-E</a><br>3. <a href="https://medium.com/@agri.kridanto/transcribe-and-translate-audio-voice-data-with-whisper-api-7b002f9672d8">Transcribe and Translate Audio Data with Whisper API</a></p><blockquote>ChatGPT: Optimizing Language Models for Dialogue</blockquote><blockquote>We’ve trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer followup questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests. ChatGPT is a sibling model to <a href="https://openai.com/blog/instruction-following/">InstructGPT</a>, which is trained to follow an instruction in a prompt and provide a detailed response. — openai.com</blockquote><p>I have tried various things, from: rephrasing a sentence/paragraph, generating outline, summarizing articles, looking for research ideas, and even generating code. It’s so promizing, I think. <strong>Honestly, I never imagined AI could be this advanced</strong>. The image below explains how the AI model of chatGPT is trained. If you want to try, please visit the openAI <a href="https://chat.openai.com/">page</a>, and click “Try ChatGPT”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hqrCxB2kZOsMCelc.png" /><figcaption>How Chat GPT trained</figcaption></figure><p>I do not discuss how chatGPT works or review the service provided by OpenAI. So far, I’ve been using ChatGPT through the PlayGround page. Then an idea emerged, “Can we access the ChatGPT service from our system ?”<strong> OpenAI provides an API that we can access through other systems</strong>. Let’s create a chatBot that communicates with chatGPT. The system will work like the scenario in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*FU5A_erkv4wV5p6Z.png" /><figcaption>System scenario</figcaption></figure><ol><li><strong>Generate ChatGPT API KEY</strong></li></ol><p>When we first register to access the ChatGPT service, we need to generate an API key. Please create a new key if you don’t have one yet, open the Settings page on the OpenAI website. <strong>Please remember this Secret key is confidential, do not share with others !!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*32jv0vW5yftCB5mV.png" /><figcaption>OpenAI API Key</figcaption></figure><p>To see the usage of Open AI services, you can access the <strong>Usage Menu</strong>. Attached is my usage for this service in the previous month. <strong>Currently, we can still use this service for free and get a credit of 18 USD</strong>. It’s worth giving a try. However, this free service has many limitations, such as daily usage limits and sometimes the service is down. It looks like a paid version of chatGPT will be released soon, as reported by <a href="https://techcrunch.com/2023/01/11/openai-begins-piloting-chatgpt-professional-a-premium-version-of-its-viral-chatbot/">TechCrunch</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*KlA0mal7xqlNXFrq.png" /><figcaption>Open AI Usage Menu</figcaption></figure><p>2. <strong>Create Telegram Bot</strong></p><p>We will use Telegram as our communication channel with ChatGPT so that we can access ChatGPT through the Telegram Platform. So, we will create a Telegram Bot via BotFather.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/0*DJ12qItXBtHi9O0s.png" /><figcaption>Create Telegram Bot via BotFather</figcaption></figure><p>Ok, please note down your bot token, because we will use the token to interact with our bot via Laravel. If you want to learn Laravel, you can read the tutorial I made on the following page (<a href="https://blog.1ln.xyz/2022/12/04/pendekin-s1e00/">Indonesian </a>or <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-part-1-e4a310afc342">English</a>).</p><p>3. Laravel Package Telegram Bot</p><p>To install a package for our Laravel project, please download it using Composer, using the syntax below.</p><pre>composer require irazasyed/telegram-bot-sdk ^2.0</pre><p>You can access the documentation at the following link.</p><p><a href="https://telegram-bot-sdk.readme.io/docs/getting-started">Getting Started</a></p><p>By using Telegram Bot and this package, there are important things that need to be considered, namely the method of communication with the Telegram Platform. If we have a system that can be accessed via the internet via <strong>HTTPS</strong> protocol, then we can use <strong>webhooks</strong>. Otherwise, we can use the <strong>Long-Polling</strong> method.</p><p>The difference if we use a webhook, Telegram will interact directly with our web via the webhook. So that if a user sends a chat/query, Telegram will immediately forward it to our website and we can carry out the actions and logic needed for the request.</p><p>However, if we don’t use webhooks, or so called the <strong>Long-Polling</strong> method, we must actively get/manage updates stored on the Telegram server. Note to remember, Telegram will only save messages from the last 24 hours.</p><p>I prefer webhooks, because they accommodate real time chat. And I use the Domainesia for my hosting, as <a href="https://medium.com/p/a8bfe90f1245">I explained in the 4th session of my article about Laravel 9</a>.</p><p><a href="https://my.domainesia.com/ref.php?u=16711">DomaiNesia Jagonya Domain &amp; Web Hosting Indonesia</a></p><p><strong>4. Laravel Package OpenAI</strong></p><p>OpenAI provides accessible API services. AFAIK, Open AI provides examples of using the API via Javascript and Python, but there is no example of use for the PHP programming language. Again, with extensive community support, Laravel has many packages that can be used. In this case, to interact with the OpenAI API. You can use the OpenAI package for Laravel and install it via Composer with the following syntax. For more detailed use of the package can be accessed via github.</p><pre>composer require openai-php/laravel</pre><p><a href="https://github.com/openai-php/laravel">GitHub - openai-php/laravel: ⚡️ OpenAI PHP for Laravel is a supercharged PHP API client that allows you to interact with OpenAI API</a></p><pre>$client = OpenAI::client(&#39;YOUR_API_KEY&#39;);<br><br>$result = $client-&gt;completions()-&gt;create([<br>    &#39;model&#39; =&gt; &#39;text-davinci-003&#39;,<br>    &#39;prompt&#39; =&gt; &#39;PHP is&#39;,<br>]);<br><br>echo $result[&#39;choices&#39;][0][&#39;text&#39;]; // an open-source, widely-used, server-side scripting language.p</pre><p>In the above code, we use the <strong>API_KEY </strong>that we got from OpenAI (Step 1). And we use the <strong>model </strong>which is <strong>‘text-davinci-3’</strong>. Meanwhile, <strong>prompts </strong>are queries/requests from us, just like our chat via PlayGround ChatGPT. Through this parameter, we will use to interact with users via the Telegram bot. Keep in mind that choosing a model is very important, because it relates to the model we use from ChatGPT, and <strong>will greatly affect the performance</strong> of the service. And, of course, <strong>related to the pricing of these services</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f88YnM7MNJnG5Bh9.png" /><figcaption>Pricing for ChatGPT Base Models.</figcaption></figure><p>5. <strong>Result</strong></p><p>From the scenario I described above, Telegram bot connects successfully with ChatGPT. Here are some of my random conversations with my new Pal :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kFagsED0Zdo-TBSl.png" /></figure><p>Ok, thats all from me, if you feel this article is helpful please share this post, claps, and follow me on Medium. Please don’t hesitate to ask in the comments section if you have any questions. Have a business idea to implement, similar with this idea? You can DM me via <a href="https://www.linkedin.com/in/agri-kridanto-03890484/">LinkedIn</a>.</p><p>Thanks, see you guys on the next posts. Have a good day !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f0ac5995452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Shortener URL with Laravel 9 — Deploy on Shared Hosting — Part 4]]></title>
            <link>https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-deploy-on-shared-hosting-part-4-a8bfe90f1245?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8bfe90f1245</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[shared-hosting]]></category>
            <category><![CDATA[laravel-9-tutorial]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[domainesia]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 14:26:14 GMT</pubDate>
            <atom:updated>2023-01-21T09:22:21.093Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918?source=your_stories_page-------------------------------------">Build Shortener URL with Laravel 9 — Deploy on Shared Hosting — Part </a>4</h3><p>Hello worlds, <br>We have built a shortener URL with Laravel 9 from the <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-implementation-of-controller-and-google-recaptcha-package-b307cea9ba00">previous posts</a>. The functionalities already implemented, we will deploy it to make this service accessible through internet. Actually, there are several ways to host a Laravel Project and in this tutorial, we will do it on Shared Hosting.</p><p>The Advantage of using Shared Hosting is that <strong>the setup is quite simple</strong> because we don’t need to set up a web server, database, php, etc. It’s already managed by the hosting providers, so we just need to manage our project. But the weakness, obviously <strong>we depend on the environment provided by this hosting provider</strong>, such as the version of the tools used.</p><p>Another drawback is that the resources on this hosting are shared with other users, as the name implies shared hosting. When the hosting provider has many users and their websites are accessed by so many visitors, the performance most likely will be degraded. Okay, here I use <a href="https://my.domainesia.com/ref.php?u=16711">Domainesia </a>for this shared hosting. There are also certain free domain features on the domainesia hosting packages.</p><blockquote>Btw, for those who want to register on Domainesia, you can use my referral code: “<strong>AGRIK</strong>”. <strong>I get a small commission from the referral</strong>, and <strong>you can get discount of up to 30%, valid forever</strong>. Not bad at all, isn’t it?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZKbE8v-ZI21TViQn.png" /><figcaption>[SAMPLE] <strong>Discount 30%, forever</strong> . Hosting on Domainesia</figcaption></figure><p><a href="https://my.domainesia.com/ref.php?u=16711">DomaiNesia Jagonya Domain &amp; Web Hosting Indonesia</a></p><p>However, if you use hosting that doesn’t have SSH features, either on Domainesia or other shared hosting, you can follow the following tutorial: <a href="https://www.domainesia.com/panduan/cara-upload-file-laravel-di-hosting/">https://www.domainesia.com/panduan/cara-upload-file-laravel-di-hosting/</a>.</p><p>In my personal opinion, it’s quite comfortable to use Domainesia, moreover, I’m using a package that has SSH features. So that was easier to deploy and use tools such as git, composer , Laravel Artisan Command, Tinker, etc. <strong>Even though it’s shared hosting, the performance is quite good</strong>.</p><ol><li><strong>PHP environment</strong></li></ol><p>Before installing Laravel, we first prepare the environment needed by Laravel, namely the PHP version and the configuration that needs to be activated via the <em>Tools Menu &gt;&gt; Select PHP Version</em>. Also we need to enable the following extensions as a prerequisites for Laravel 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HdxByfhzmS1oUFkP.png" /><figcaption>Select PHP Version on Domainesia CPANEL</figcaption></figure><p>— BCMath PHP Extension <br> — Ctype PHP Extension <br> — DOMPHP Extensions <br> — Fileinfo PHP Extension <br> — JSON PHP Extension <br> — Mbstring PHP Extension <br> — OpenSSL PHP Extension <br> — PCRE PHP Extension<br> — PDO PHP Extension <br> — PHP Extension <br> — Tokenizers XML PHP Extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mK1xqdDz2yXYiKa1.png" /><figcaption>Select PHP version and enable PHP Extensions</figcaption></figure><p><strong>2. Domain Setup </strong><br>To set up the domain, we access the Domain menu on CPANEL and we specify the folder where our Laravel project is set up. In that folder, we place the Laravel project in the ‘pendekin’ folder.</p><blockquote>*In the next stage, I will use ‘1ln’ folder, to be able to provide screenshots and simulate the configuration process.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IzWphSiZFlglXI2-.png" /><figcaption>domain set up on CPANEL</figcaption></figure><p><strong>3. MySQL Database Setup </strong><br>Next, let’s create the MySQL database. You can follow the following tutorial: <a href="https://www.domainesia.com/panduan/panduan-buat-database-mysql-di-cpanel/">https://www.domainesia.com/panduan/panduan-buat-database-mysql-di-cpanel/</a>, to determine the database name, user, and password. After getting it, we can include these variables in <em>.env</em> file .</p><p><strong>4. Set Up Laravel Project via SSH </strong><br>We will use SSH to upload to shared hosting. The SSH setup can be seen in the Domainesia tutorial, at the following link: <a href="https://www.domainesia.com/panduan/cara-access-ssh-di-cpanel-hosting/">https://www.domainesia.com/panduan/cara-access-ssh-di-cpanel-hosting/</a>. After entering SSH, we can install our project.</p><p><strong>— Clone from the repository</strong> <br>The code that we created, with the following repository address: <a href="https://github.com/agriirga/pendekin.git">https://github.com/agriirga/pendekin.git</a>. We can clone it with the following syntax in the SSH terminal: git clone <a href="https://github.com/agriirga/pendekin.git">https://github.com/agriirga/pendekin.git</a> 1ln . The 1ln is the name of the folder that we will use when we clone from the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*JxNjJJMV-g970Laf.png" /><figcaption>clone project with ssh on 1ln folder</figcaption></figure><p><strong>— Download Project Dependencies</strong><br>As we have learned before, we can download the dependencies of this project using the composer update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*4t6CbmzkcNRVMDEZ.png" /><figcaption>download project dependencies through composer update</figcaption></figure><p><strong>— Create a .env file </strong><br>Execute the following command :</p><pre>cp .env.example .env</pre><p>To create a <em>.env</em> file from an example <em>.env.example</em> file. Don’t forget there are important things that we set up yesterday in the project, namely: DB configuration and ReCaptcha configuration. Let’s customize the <em>.env</em> file on this server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*9cRkvjwNqP92ZFU6.png" /><figcaption>Add information on .env file</figcaption></figure><p>We also need to change these .env variables</p><pre>APP_DEBUG = FALSE <br>APP_URL=https://1ln.xyz </pre><p>We set <em>APP_DEBUG</em> as false so that the display of errors/bugs in our application does not appear to our users, considering that this application can be accessed by the public. For trace errors, we can look at <em>storage&gt;&gt;logs&gt;&gt;laravel.log . </em>Meanwhile, we modify the <em>APP_URL </em>to the domain name or subdomain that we use, in this example: <a href="https://1ln.xyz/">https://1ln.xyz</a>.</p><p>For reCaptcha configuration, you can create a new configuration or change an existing one. Similar to the previous tutorial, what must be considered is the domain of our application. Here I add my domain, namely ‘<strong>1ln.xyz</strong>’ .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/0*24tfUeSXkQRSY9jY.png" /><figcaption>reconfig ReCaptcha keys for our hosting</figcaption></figure><p>When done, please attach it to the .env variable. Next, we need to generate the encryption key used in our application by running this artisan command:</p><pre>php artisan key:generate</pre><p><strong>— Database Migration</strong><br>Run the artisan command to generate a database via the Laravel migration with this command :</p><pre>php artisan migrate</pre><p><strong>— Configuration .htaccess File</strong></p><p>In the project folder that we created earlier, we need to create the .htaccess file as follows:</p><pre>touch .htaccess</pre><p>In that file, include the following script so that our Laravel project can be accessed via the domain or subdomain that we specify.</p><pre>&lt;IfModule mod_rewrite.c&gt;<br><br>        RewriteEngine On<br><br>        RewriteRule ^(.*)$ public/$1 [L]<br><br>&lt;/IfModule&gt;</pre><p>Voila, now our web can be accessed via the internet. As an example of a project, you can access this website on this page <a href="https://1ln.xyz/">https://1ln.xyz</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5Z4dQtghIVBpAtICI5jtQ.png" /><figcaption>https://1ln.xyz</figcaption></figure><p>Ok, I think thats enough for this tutorial series. <strong>We already learn Laravel 9 and build shortener URL project and deploy it to internet</strong>. If you feel this tutorial series is helpful, please share , clap, and follow me on Medium.</p><p>Have any questions or suggestions about this <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-part-1-e4a310afc342">tutorial series</a> ? You can hit me in the comments below. That’s all I thought, hopefully, we can learn more in next times. Cheers .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8bfe90f1245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Shortener URL with Laravel 9 — Implementation of Controller and Google ReCaptcha Package —…]]></title>
            <link>https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-implementation-of-controller-and-google-recaptcha-package-b307cea9ba00?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b307cea9ba00</guid>
            <category><![CDATA[controller]]></category>
            <category><![CDATA[laravel-9-tutorial]]></category>
            <category><![CDATA[recaptcha]]></category>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[laravel-packages]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 11:52:42 GMT</pubDate>
            <atom:updated>2023-01-17T15:49:50.085Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918?source=your_stories_page-------------------------------------">Build Shortener URL with Laravel 9 — Implementation of Controller and Google ReCaptcha Package — Part </a>3</h3><p>In this tutorial, we will discuss Controllers in the Shortener URL project we are developing. In the <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918">previous session</a>, we learned about Database &amp; Models, and Views. In this tutorial, we will continue to work with those two components and also explore the use of Laravel Packages to implement Captcha</p><ol><li><strong>Add Packages Google ReCaptcha</strong></li></ol><p>The application we developed in this tutorial does not have user functionality to login, thus allowing anyone including bots, to access the shortener service created. To address this problem, we will use Google ReCaptcha v2 which is already proven and one of the best practices for this case. <br>Google Recaptcha would ask the user to solve the challenge for image identification. It aims to identify that the user is not a bot. Interestingly, we can easily implement this functionality thanks to this package: <a href="https://github.com/anhskohbo/no-captcha">https://github.com/anhskohbo/no-captcha</a>.</p><p><a href="https://github.com/anhskohbo/no-captcha">GitHub - anhskohbo/no-captcha: No CAPTCHA reCAPTCHA For Laravel.</a></p><p>A. <strong>Install packages</strong></p><p>In this stage we will install the Laravel no-captcha package by using Composer in this project. Open a terminal at the root of the project and install it with the following command:</p><pre>composer require anhskohbo/no-captcha</pre><p><strong>B. Create Google ReCaptcha Configuration</strong></p><p>To be able to take advantage of Google ReCaptcha, we need to register for the service to get the site and secret key that we will use in our project via the following link: <a href="https://www.google.com/recaptcha/admin">https://www.google.com/recaptcha/admin</a>. <br>Please read the Terms of Use before using this service :) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6CVd_COx0ivDeEr-.png" /><figcaption>Get ReCaptcha Site and Secret Key</figcaption></figure><p>I think it’s easy to fill in the form. What is noteworthy is the domain, because now we are still on our local PC. So let us enter the local domain, for example, <a href="https://pendekin.test/">https://pendekin.test</a>. If we are going to upload it to the server later, we need to reconfigure it. Remember this is <strong>confidential information of your settings</strong>, <strong>so we need to put this key in <em>.env</em> file. </strong>Ok, that’s enough for package installation. Let’s move to the Controllers part</p><pre>NOCAPTCHA_SITEKEY=[your site key]<br>NOCAPTCHA_SECRET=[your secret key]</pre><p><strong>2. Controller</strong></p><p>Let’s start by creating a controller by running the artisan command as follows:</p><pre>php artisan make:controller ShortlinkController --resource</pre><p>The artisan command will generate a Controller file named <em>ShortlinkController</em>. The --<strong><em>resource</em></strong> flag is used to create a controller with methods for handling standard resource operations such as index, create, store, show, edit, update, and delete rather than having to manually create all the methods.</p><p>After we create the controller, we need to define a route in <em>routes&gt;&gt;web.php</em> to access the controller. Take note of lines 4 and 17, where we will use the shortlink resource route which will access the ShortlinkController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oz_gS4sx-b6LFKAm.png" /><figcaption>route:resources in web.php for ShortLinkController</figcaption></figure><p>To be able to see the correlation, execute the following Artisan Command in the terminal:</p><pre>php artisan route:list</pre><p>In the item in the red box, it explains the relationship between the route and the controller that we created. For example, if we access ‘<em>/shortlink</em>’ with the POST method, the router will route the request to the <em>ShortlinkController </em>in the <em>store()</em> function. We will use these routes and functions to generate short links that are inputted by the user. There is also a named route with the name ‘<strong>shortlink.store’</strong> that we can use to access our route, more concisely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0dD6NiCiSgwmdWYn.png" /><figcaption>list of routes defined in our project</figcaption></figure><blockquote>Btw, you can create an empty controller without the default functions on the controller as we have demonstrated here. Rather than to define routes without route resources. I gave an example of the use above because it is very applicable if we need it.</blockquote><p>Let’s try to use the named-route <strong>shortlink.store </strong>(<strong>Line 7 on Screenshot below </strong>) to access our website. And we use the POST method so that we are directed to the <em>ShortlinkController </em>in the <em>store()</em> function according to the following code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ACQcHFoQOgHVgSFr.png" /></figure><p>To check whether it is what we expect, we can use the <em>dd($request)</em> method in the <em>store()</em> function. The dd() or die dump function is used to inspect the variables and halt the execution of the next code statement. This function is particularly useful when troubleshooting errors in our code.</p><pre>public function store(Request $request)<br>{<br>  dd($request);<br>}</pre><p>In this code, the controller accepts the <em>$request </em>variable sent via the form. As we can see, the variables ‘<em>token</em>’ and ‘<em>urlAddress</em>’ are sent through the form and captured by this<em> die dump</em> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UGqyIl6dPRhCKOtw.png" /><figcaption>result of dd($request)</figcaption></figure><p>Next, we need to perform validation to ensure that<strong> the form is filled in with a valid URL</strong>. Let’s add the following code in the store() method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*dT2MyM4B8sWqE4r_.png" /><figcaption>validation of urlAddress is required &amp; must be in URL format (http:// or <a href="https://)/">https://)</a></figcaption></figure><p>If we submit the form without filling in the URL, we will not reach the code on line 7 and be redirected back to the start page. Similarly, if we fill in a random string that is not in the URL format, the form validation will also reject it. This is because the urlAddress variable must be filled in and be in the URL format (e.g. <a href="http://blablabla/">http://blablabla</a> or <a href="https://blablabla/">https://blablabla</a>). If we fill in the form correctly, the code on line 7 will execute and display the $request information. It’s pretty simple, right?</p><p>Okay, this feature is useful, but how to display the error message? We will modify our views file as follows. <strong>At the screenshot below, Lines 22 to 32 </strong>we use the ‘<em>@if’</em> and ‘<em>@endif’ </em>which is blade directives to check whether there are errors sent from the Controller. And blade directives <em>@foreach</em> and <em>@endforeach</em> to iterate over the error messages. Keep in mind, during the validation in the controller, we can do a lot of checking on the request variables sent through the form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ruK3BlToUOQWjylX.png" /><figcaption>add blade directive in order to show error message from validation</figcaption></figure><p>Ok, that was basic example of Validation, let’s add another validation such as : length of short URL, shorten URL must be unique and ReCaptcha Response is required. To implement this functionality we need to modify our form. So, let’s add <em>jquery.min.js</em> from the<em> </em>CDN so we can implement Google ReCaptcha.</p><pre>&lt;body&gt; <br>.........<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;</pre><p>I decomposed <em>contents.blade.php</em> to separate the form from other contents., so we have <em>form.blade.php</em> and <em>contents.blade.php</em>. In this form, we implement Laravel package <em>Google ReCaptcha</em> on <strong>Line 36</strong> and<strong> Line 49</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*AL3BowytjP5pt1kI.png" /><figcaption>form.blade.php</figcaption></figure><p>Next, we include that form into <em>contents.blade.php</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*dqlmq62-vOorVkjm.png" /><figcaption>contents.blade.php</figcaption></figure><p>Let’s see, the reCaptcha form should have appeared on our page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TUx5FQ3XmKUGAEKK.png" /><figcaption>google ReCaptcha added</figcaption></figure><p>We would add the expected shortUrl from the user, so that this service <strong>doesn’t just provide a random short URL, if the user wants it</strong>. Therefore we add forms and controllers for these requirements. The following code changes to <em>form.blade.php</em>. On <strong>Lines 45 to 48</strong> we provide the expected short URL input form, if the user wants. <strong>This field is not mandatory</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*ntWZNhL9MU84MEN5.png" /></figure><p>Apart from changing the view, we need to change the controller, especially in the validation section.</p><blockquote>— The shortUrl must be between 3 to 15 characters and must be unique in shorted_links table on short_url column. <strong>This is needed so the short_url is unique</strong></blockquote><blockquote>— The ReCapctha must be filled / answered it by user.</blockquote><p>If validations pass, we would check whether a user specifies the expected short URL and we would store it in the database. But if the user does not specify the expected short URL, we would create a random string (in this case, 5 characters). We also check if the random character generated already stored / added in shortUrl column in DB to make sure the variable is unique.</p><pre>public function store(Request $request)<br>{<br>    $validated = $request-&gt;validate([<br>        &#39;urlAddress&#39; =&gt; &#39;required|url&#39;,<br>        &#39;shortUrl&#39; =&gt; &#39;min:3|max:15|nullable|unique:shorted_links,short_url,&#39;,<br>        &#39;g-recaptcha-response&#39; =&gt; &#39;required|captcha&#39;,<br>    ]);<br>    /*<br>        If short Url is not specified, generate Random String with 5 chars<br>    */<br>    if(!$request-&gt;shortUrl)<br>        $short_url = $this-&gt;generateShortUrl(5);    <br>    else<br>        $short_url = $request-&gt;shortUrl;<br><br>    /* insert to DB */<br>    $url = ShortedLink::create([<br>        &#39;short_url&#39; =&gt; $short_url,<br>        &#39;long_url&#39; =&gt; $request-&gt;urlAddress<br>    ]);<br>    $short_url = url(https://medium.com/&#39;&#39;) .&#39;/&#39;. $url-&gt;short_url;<br>    return back()-&gt;with(&#39;success&#39;, $short_url);<br>}<br><br>/*<br>    Function to generate URL in random string n characters <br>    and check whether string already stored in DB<br>*/<br>public function generateShortUrl($jumlah_karakter){<br>    <br>    while(true){<br>        // generate short url<br>        $short_url = Str::random($jumlah_karakter);<br>        <br>        // check the string already added in DB<br>        $is_exist = ShortedLink::where(&#39;short_url&#39;, $short_url)-&gt;first();<br>        <br>        if(!$is_exist){<br>            // if not return this random string<br>            return $short_url;<br>        }<br>    }<br>}</pre><p>Finally, we would add buttons to perform the copy function to make it easier for users to copy the shortened URL. Also, we would add sharing via WhatsApp and Telegram to add user experience. Okay, we need to add FontAwesome to our project by utilizing Contents Delivery Networks (CDN) of FontAwesome at <em>resources&gt;&gt;views&gt;&gt;layout&gt;&gt;app.blade.php</em></p><pre>&lt;!-- Font Awesome CDN   --&gt;<br><br>&lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;</pre><p>By using a CDN, we will use the CSS provided via the link above, not accessing it directly in our project folder. If you guys don’t want to use a CDN, please download the required files at <a href="https://fontawesome.com/download">https://fontawesome.com/download</a>.</p><p>Put it in the<em> public&gt;&gt;css </em>folder and don’t forget to also adjust sample code above to access the CSS at <em>resources&gt;&gt;view&gt;&gt;layout.app.blade.php</em>. Next, we add the button in <em>forms.blade.php </em>. We add three buttons <strong>CopyText</strong>, <strong>Share on Whatsapp</strong>, and <strong>Share to Telegram</strong> respectively to call the Javascript function at on-click . The following codes at <em>forms.blade.php, </em>each button will call the Javascript function in <em>contents.blade.php.</em></p><pre>@if(Session::has(&#39;success&#39;))<br>    <br>    &lt;div class=&quot;col-md-12 alert alert-success&quot;&gt;<br>    &lt;label id=&quot;lblShortUrl&quot;&gt;{{Session::get(&#39;success&#39;)}}&lt;/label&gt; <br>    &lt;button class=&quot;btn btn-info ms-2&quot; id=&quot;btnCopy&quot; onclick=&quot;copyText()&quot;&gt;<br>        &lt;i class=&quot;fa-solid fa-copy&quot;&gt;&lt;/i&gt;<br>    &lt;/button&gt;     <br>    <br>    &lt;button class=&quot;btn btn-success ms-2&quot; id=&quot;btnWhatsapp&quot; onclick=&quot;shareOnWhatsApp()&quot;&gt;<br>        &lt;i class=&quot;fa-brands fa-whatsapp&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;<br>        <br>    &lt;/button&gt;<br>    &lt;button class=&quot;btn btn-primary ms-2&quot; id=&quot;btnTelegram&quot; onclick=&quot;shareOnTelegram()&quot;&gt;<br>        &lt;i class=&quot;fa-brands fa-telegram&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;<br>    &lt;/button&gt;<br>    &lt;/div&gt;  <br>@endif</pre><pre>&lt;script&gt;<br>  function copyText() {<br>// Get the text to be copied<br>    var link = document.getElementById(&quot;lblShortUrl&quot;).innerText;<br>    // Create a temporary element to hold the text<br>    var tempInput = document.createElement(&quot;input&quot;);<br>    tempInput.value = link;<br>    // Add the element to the document and select the text<br>    document.body.appendChild(tempInput);<br>    tempInput.select();<br>    // Copy the text<br>    document.execCommand(&quot;copy&quot;);<br>    <br>    // Remove the element from the document<br>    document.body.removeChild(tempInput);<br>    alert(&#39;Shortlink Copied to Clipboard: &#39; + link);<br>    <br>  }<br>  function shareOnWhatsApp() {<br>    // Get the text to be copied<br>    var link = document.getElementById(&quot;lblShortUrl&quot;).innerText;<br>    // Open a new window to the WhatsApp share URL<br>    window.open(&quot;https://wa.me/?text=&quot; + link);<br>  }<br>  function shareOnTelegram() {<br>    // Get the text to be copied<br>    var link = document.getElementById(&quot;lblShortUrl&quot;).innerText;<br> <br>    // Open a new window to the Telegram share URL<br>    window.open(&quot;https://t.me/share/url?url=&quot; + link  );<br>  }<br>&lt;/script&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAITrIvZosepmJcZx2UXSw.png" /><figcaption>funtionalities added !!</figcaption></figure><p>We have generated short URL, now we will create a method to redirect the shortlink to the original url. Put this code at web.php in order to add new route. So, if someone visit the route with shortened URL given from this website, the router will access the <em>ShortLinkController</em> on <em>redirectTo</em>() method.</p><pre>Route::get(&#39;/{shorturl}&#39;, [ShortLinkController::class, &#39;redirectTo&#39;])-&gt;name(&#39;shortlink.redirectTo&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jR-PQ8fUEQNGUHJ6.png" /><figcaption>redirectTo() method on ShortLinkController</figcaption></figure><p>On <em>Line 2</em> in the screenshot above, we perform a select query on the <em>ShortedLink </em>Model according to the <em>shortUrl </em>parameter given by the <em>firstOrFail</em>() method. The method will return an error not found (<em>404</em>) if the requested data is not found. Otherwise, iwe will be redirected to original URL. In addition, we also add a counter by utilizing <em>increment </em>method , from Eloquent ORM, every time the link is visited (<strong>Line 4</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XBtpxXVVQFtWwydp.png" /><figcaption>404 Not Found Page, if shortened URL is not registered on our website</figcaption></figure><p>Inside of the landing page, we display 2 metrics, which are the number of generated shortlinks and the number of visitors who visited the shortlink. Therefore we change the landing page route as follows, to be able to perform the required queries on the Controller.</p><pre>Route::get(&#39;/&#39;, [ShortLinkController::class, &#39;landing&#39;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UvQSCCDXI_YipgPM.png" /><figcaption>landing() method on ShortLinkController</figcaption></figure><p>In <strong>Line 6 </strong>we use the count function in Eloquent to count the number of rows in the ShortedLink Model. Meanwhile, <strong>Line 7</strong> does the sum of the counter columns, with the sum function from Eloquent, in the <em>ShortedLink</em> model. Next, these 2 variables will be thrown into views<em> landing.blade.php</em></p><p>Ok, I think thats enough for this tutorial. We already learn how to use Laravel Package Google ReCaptcha and implement Controller for our project. If you feel this tutorial is helpful, please share this post, clap, and follow me on Medium.</p><p>Please don’t hesitate to ask in the comments and thank you very much. See you guys on the next <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-deploy-on-shared-hosting-part-4-a8bfe90f1245">posts</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b307cea9ba00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Shortener URL with Laravel 9 — Model & View Implementation — Part 2]]></title>
            <link>https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2aed57a2918</guid>
            <category><![CDATA[laragon]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[laravel-development]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 04:08:55 GMT</pubDate>
            <atom:updated>2023-01-18T13:22:14.606Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-part-1-e4a310afc342?source=your_stories_page-------------------------------------">Build Shortener URL with Laravel 9 — </a>Model &amp; View Implementation — Part 2</h3><p>Hello World,</p><p>In this tutorial, we will continue our series on building a web Shortener URL while learning Laravel 9. <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-part-1-e4a310afc342">In the previous post</a>, we explained the Environment Development of our Project, the MVC architectural pattern, and the project structure on the Laravel-based Web that we are building.</p><p>In this blog post, We will focus on implementing the Model-View-Controller (MVC) pattern in our project. I would put Controller implementation in the next <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-implementation-of-controller-and-google-recaptcha-package-b307cea9ba00">post</a>.</p><ol><li><strong>Model </strong><br>We will delve into the subject of databases and model.</li></ol><p><strong>A. Database Design</strong></p><p>This website has simple functionality, so the database built here is also simple. As we mentioned before, we will use is MySQL as our database in this project. If you are using Laragon, it comes pre-installed with MySQL as we previously discussed in our last post.</p><p>The primary purpose of this web application is to provide shortened versions of URLs. We will create a unique shortened URL for each user request and store it in our database. Additionally, we will keep track of the number of times each shortened URL is accessed, as well as the last accessed timestamp. Below is the table design that we will use to accomplish this functionality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/0*dpDgOvml2j3NTPs_.png" /><figcaption>database design for shortener url</figcaption></figure><p>The above table design has the following columns:</p><blockquote>— <strong>id</strong>: Primary Key column of this table. has a big integer data type and is auto-increment<br> — <strong>long_url</strong>: has a string data type, which will be used to store the URL submitted by the user.<br> — <strong>short_url</strong>: has a string data type, used as a shortening URL.<br> — <strong>counter</strong>: has data type integer, which will be used to count the number of times this URL has been accessed via this short URL.<br> — <strong>last_visit</strong>: has a timestamp data type, which states the last time the link was accessed via this short URL.<br> — <strong>created_at, updated_at, deleted_at</strong>: have a timestamp data type, which states when the row was created, updated, and deleted.</blockquote><p><strong>B. Database Setup and Configuration</strong></p><p>FYI, Laravel is a database-agnostic framework, so it means that it allows for the use of various databases, including SQLite, MySQL, Postgres, and MS SQL. Laravel provide Eloquent as an Object-Relational Mapper (ORM) to simplify interactions with the database. We will create a MySQL database, which comes pre-installed with Laragon. To do this, open the Laragon application and press the ‘Database’ button to create the MySQL database that we will use in this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*F2lXZqBqWp2a_DTl.png" /><figcaption>access DB Client , Heidi SQL, from Laragon main menu</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*29-H3mLy4adwwLR8.png" /><figcaption>Create MySQL database from Laragon’s Heidi SQL</figcaption></figure><p>Input the desired name for the database, for example “db_pendekin”. Once entered, the database will be created. Next, we need to change the <em>.env</em> file in our laravel project so that it can connect to the database we created. Open the .env file in our project and change the DB settings as follows :</p><pre>DB_CONNECTION=pendekin<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=db_pendekin<br>DB_USERNAME=root<br>DB_PASSWORD=</pre><p>The settings specified above are for configuring the database that we will be using in this project. We have named the connection “<strong>pendekin</strong>”, and are using the <strong>MySQL database</strong>, on the IP address of <strong>127.0.0.1 </strong>(which is our localhost/pc) and can be accessed via port <strong>3306</strong>. The database name is the one we previously created, in this case, “db_pendekin”. Also, we provide the <strong>username and password </strong>to access the database. Since it’s still localhost, it does not pose a security risk to include this information in this post.</p><p>The database configuration used can be found in <em>config&gt;&gt;database.php </em>. I made slight modification on <strong>lines 18</strong> and <strong>lines 38 to 55</strong> for easier explanation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JP52ZreI7nPrYGA2.png" /><figcaption>config/database.php</figcaption></figure><p>The code indicates that we are utilizing the ‘pendekin’ connection as specified in the ‘DB_CONNECTION’ variable within the .env file. If the ‘DB_CONNECTION’ variable is not found in the .env file, then the second option will be used, which is ‘<strong>mysql</strong>’.</p><p>This ‘<strong>pendekin</strong>’ configuration located “connections” array (<strong>Line 38 in <em>config&gt;&gt;database.php</em></strong>). In the configuration files, it also references variables from the .env file. If the variable is defined in <em>.env</em>, it will use that value. Otherwise, it will take the second option/parameter.</p><p>It’s is important to note, unlike the <em>.env</em> file that should not be submitted to the repository. The <em>config&gt;&gt;database.php</em> file typically stored in the repository. Therefore, it’s considered best practice to store the credentials in the .env file. For a more detailed explanation, you can refer to the Laravel documentation at this <a href="https://laravel.com/docs/9.x/database#configuration">link </a>.</p><p><a href="https://laravel.com/docs/9.x/database#configuration">Laravel - The PHP Framework For Web Artisans</a></p><p><strong>C. Model &amp; Migration</strong></p><p>After we know the database design that we will create, we can use Migration in Laravel. This migration feature is provided by Laravel to generate database schemas through Laravel directly. This simplifies the process of set up or alter tables, as it can be done through the use of code rather than use a separate database client. Additionally, the code used in this process can be easily adapted to work with different databases such as Postgres or SQLite.</p><p>Let’s try, open Laragon’s terminal and type the following command:</p><pre><br>php artisan make:model ShortedLink -m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m2gY91aTkP6Mik4M.png" /><figcaption>generated files by executing that commands</figcaption></figure><p>The command above is an Artisan Command to generate Schema migrations and Models for the <em>shorted_link </em>table. There are 2 files generated by executing the command.</p><blockquote><em>If you want to create migrations and models separately, you can use the artisan commands </em><strong><em>make:migration</em></strong><em> and </em><strong><em>make:model</em></strong>.</blockquote><p>—<strong> Migration</strong></p><p>The migration files are stored in the <em>database&gt;&gt;migrations</em> folder. Here is the code for our migration and I think it’s quite easy to understand the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*KMsJ0rQgRvvCEzE1.png" /><figcaption>migration code for ‘shorted_links’ table</figcaption></figure><blockquote>— Line 16, we will create a table named ‘<strong>shorted_links</strong>’.<br> — Line 17, we will generate <strong>auto increment</strong> for this table.<br> — In line 19, we define the short_url field, with a data type of varchar up to <strong>15 characters</strong>. Please adjust to your needs.<br> — Line 20 will generate a counter column with an <strong>integer </strong>data type that has a <strong>default value of 0</strong>.<br> — Line 21 will generate the column last_visit which has the data type timestamp and is <strong>nullable</strong>, <strong>which is not mandatory/ required </strong>when we create a row in this table.<br> — Line 22 will generate <strong>3 timestamp columns</strong>, namely: <strong>created_at, updated_at</strong>,.<br> — Line 23 will generate column <strong>deleted_at </strong>with <strong>timestamp </strong>data type</blockquote><p>Next, we need to execute this migration to create tables in the database via the following command:</p><pre>php artisan migrate</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*THnzf5VDcrReZG7d.png" /><figcaption>php artisan migrate</figcaption></figure><p>As illustrated in the image above, five tables have been created. The additional four tables are pre-built in Laravel and have not been used in this tutorial for the sake of simplicity. If you open the Heidi SQL application, you will see those five tables. You can view the ‘<em>shorted_links</em>’ like the image below. If you wish to learn more about using migrations, you can refer to the official Laravel documentation at this <a href="https://laravel.com/docs/9.x/migrations">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EqMcvBBc-VvWWFQG.png" /><figcaption>table generated from migration</figcaption></figure><p><a href="https://laravel.com/docs/9.x/migrations">Laravel - The PHP Framework For Web Artisans</a></p><p><strong>— Models</strong></p><p>Remember the Model in the MVC concept? Yes, Models are used to interact with databases. According to the tutorial above, we already have one model generated via the Laravel Artisan Command above. These models can be accessed in the <em>App&gt;&gt;Models&gt;&gt;ShortedLink.php</em> .</p><p>The file interacts directly with the ‘<em>shorted_links</em>’ table. By examining the file names generated by the commands, we can identify the naming conventions used by the framework. The Model class created follows the convention of using singular nouns and <a href="https://en.wikipedia.org/wiki/Camel_case">CamelCase</a>, while the table generated through migration uses a plural noun and <a href="https://en.wikipedia.org/wiki/Snake_case">snake_case</a>. When using English, it is recommended to follow these conventions as it aligns with Laravel’s naming conventions.</p><p>Let’s take a look at the ShortedLink.php file, in the code, it doesn’t say which table is related. If we follow the Laravel naming conventions above then there’s no problem. But if we don’t, we need to write it explicitly (<strong>Line 14</strong>).</p><p>Next, we also need to determine which fields we can fill in through the Model. Because by default, <strong>Model does not allow fields to be filled in directly</strong>, we need to specify which fields we can fill in, via the <em>$fillable </em>or <em>$guarded</em> property. If we use <em>$fillable</em>, it means that we need to explicitly specify which fields we can fill in. On the other hand, if we use <em>$guarded</em>, we need to fill in any columns that cannot be filled in by the user, for example, the id column as the Primary Key (PK) in this table.</p><p>In the code below, we write that the fields <em>‘long_url’, ‘short_url’, ‘counter’, ‘last_visit’</em> can be filled (<strong>Line 16</strong>). We also use <em>SoftDeletes </em>to flag deleted rows (<strong>Line 7 and Line 12</strong>). The following is the code for the <em>ShortedLink.php</em> model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*IX2CbZeqIOgNaP6E.png" /><figcaption>ShortedLink Model</figcaption></figure><p>To test the interaction with the database, we can use <a href="https://laravel.com/docs/9.x/artisan#tinker"><strong>Tinker </strong></a>and <a href="https://laravel.com/docs/9.x/eloquent"><strong>Eloquent</strong></a> ORM. Tinker is a command line interface (CLI) in Laravel that we can use to execute code with the PHP programming language. This tool is very practical, we can use them to check code statements in the PHP language more briefly.</p><p>Meanwhile, Eloquent is an Object Relational Mapper that we use to access the database we have defined. By using Eloquent, we can use the same code, even though the database used is different. The code used is very intuitive and easy to understand. Okay, we will demonstrate inserting data using a model through Tinker in the terminal.</p><pre>php artisan tinker</pre><p>Use the following code to insert new data into the shorted_links table.</p><pre>$url = App\Models\ShortedLink::create([&#39;long_url&#39;=&gt;&#39;blog.1ln.xyz&#39;,&#39;short_url&#39; =&gt; &#39;blogini&#39;]);</pre><p>The above code uses the Eloquent ORM to insert a row to database. We can see that by default Eloquent also fills in the <em>created_at and updated_at </em>columns. Let’s try updating the row using Eloquent as follows. We do a select query and then do an update. Is it easy to understand the syntax, isn’t it ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*MVtsE4ZKK4z8wYvu.png" /><figcaption>Updating data using Model through Tinker CLI</figcaption></figure><p>We can also update with one line code / chaining code as follows.</p><pre><br>$links = App\Models\ShortedLink::where(&#39;short_url&#39;,&#39;mylink&#39;)-&gt;update([&#39;counter&#39; =&gt; 4]);</pre><p>Next, let’s try a delete query, like the terminal screenshot below. The <em>deleted_at </em>column will be filled if we use the delete command. We can use the following code to delete via Models with Eloquent ORM. (<em>Remember, we are using SoftDeletes on the Model we have created</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*pY_MMkEiAsvONpFO.png" /><figcaption>Deleting data using Model through Tinker CLI</figcaption></figure><p>Next, let’s try the following code, to get row data where the column <em>long_url </em><strong>has the extension “.xyz”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gJmIZeTQmdbpPS51.png" /><figcaption>Select data using Model through Tinker CLI</figcaption></figure><p>The code is equivalent to the following SQL query:</p><pre>select * from shorted_links where long_url like &#39;%.xyz&#39;</pre><p>There are still many Eloquent features that are very useful and can make it easier for us to develop applications with the Laravel Framework. For more details, you can access Laravel Official docs in this <a href="https://laravel.com/docs/9.x/eloquent">link</a></p><p><a href="https://laravel.com/docs/9.x/eloquent">Laravel - The PHP Framework For Web Artisans</a></p><p><strong>2. Views</strong></p><p>In Views, we’ll focus on the view side of our web page. Of course, later it will also interact with the Route and Controller. But in this session, we will focus more on making the appearance first.</p><p>For its appearance, we will make it simple. On the main page, we will provide an input form and a button to generate short links according to the main functionality of the application being built. Okay, it’s easier for us to take an example of landing page template as provided by Start Bootstrap on this <a href="https://startbootstrap.com/theme/landing-page">link</a>.</p><p><a href="https://startbootstrap.com/theme/landing-page">Landing Page - Free Bootstrap 5 Landing Page Theme</a></p><p>I think the template fits our needs and mobile-friendly. Okay, let’s just download via that link, and extract files and move to public folder. So the structure of the folder should look like the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*vUfXkyHGIjIZQM5M.png" /><figcaption>add UI template to public folder</figcaption></figure><p>We need to make some modifications in the style.css file, related to the position (path) of the assets file that we have adjusted, which are located in public folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EJBsdKEExLgvhpw_.png" /><figcaption>header.masthead</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iBtM1rSwOBK0cqSH.png" /><figcaption>.call-to-action</figcaption></figure><p>After that, we copy and paste the index.html file into the <em>resources&gt;&gt;view&gt;&gt;sb.blade.php</em> . The <strong><em>.blade.php</em></strong> is an extension of the views file in Laravel. Remember the previous file that contains Laravel documentation? Yup, the filename is <em>welcome.blade.php</em>. Now, let’s go to <em>routes/web.php</em> and update the route as follows..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0LVK4pObM4pQtQP7.png" /><figcaption>web.php</figcaption></figure><p>Ok, now we have 3 routes, each of them accessing a different view. Route <em>/start_bootstrap </em>to access the Start Bootstrap page we set up earlier. <br>I think we don’t need all the sections in the template earlier. I will only user 4 sections on the landing.blade.php page, which are:</p><blockquote>—<strong> Masthead</strong>, we use this as a form submit by the user to generate short links<br> —<strong> Icons</strong>, we will use this to show the number of short links that we have generated and the number of visitors who visit short links through this website. <br> — <strong>Image Showcases</strong>, this section is static, we write down the benefits of this website, like : Easy To Remember, Forever Free, and Always Accessible<br> —<strong> Footer</strong>, in this section we will display the footer of this web, such as copyrights and links to our social media.</blockquote><p>However, feel free to use other sections if you prefer. Let’s try to access the main page on this web, it should match with our expectations. On the main page, the Icons section will display variables that will be processed from Route to Views. Let’s begin by customizing our route first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PE3cgoH-01fT5bGG.png" /><figcaption>sending variable from routes to views</figcaption></figure><p>In the code above, we set up 2 variables, namely <em>$shortlink_count</em> and <em>$visitor_count</em> to be sent to views <em>landing.blade.php</em> using the compact function provided by Laravel. Don’t forget to write it <strong>using the string from the variable name</strong>. Next, we will change the side view <em>landing.blade.php</em></p><p>In the code views, above, we will display the variables sent by the route namely <em>{{$shortlink_count}}</em> and <em>{{$visitor_count}}</em> . The directive <em>{{ $variable }}</em> is a Blade Directive which similar with<em> php echo $variable</em>. Now let’s try to use other Blade features so that the display is more modular by creating a skeleton from the page we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jYJjHIs-aBMns7Tl.png" /><figcaption>landing.blade.php</figcaption></figure><p>Let&#39;s create a file in <em>resources&gt;&gt;view&gt;&gt;layouts.app.blade.php</em> file. In that code, we create an HTML skeleton for our page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NXw376DCohw13Y9s.png" /><figcaption>app.blade.php</figcaption></figure><blockquote>On line 19 we provide a place/section namely <strong>&#39;contents&#39;</strong> to fill in content from this landing page. <br> On line 20, we add/attach a <strong>footer </strong>to this skeleton</blockquote><p>Let’s try to create a file in <em>resources&gt;&gt;views&gt;&gt;layouts&gt;&gt;footer.blade.php</em> with the following code. The code matches the StartBootstrap template that we previously downloaded, but only in the footer section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxSxIOY1GB6A04iz.png" /><figcaption>footer.blade.php</figcaption></figure><p>With the code above, our skeleton already has a footer. But we haven’t prepared the content yet. Let’s prepare it by creating the following file <em>resources&gt;&gt;views&gt;&gt;layouts&gt;&gt;contents.blade.php </em>It contains <strong>Mastheads </strong>(for URL input form), <strong>Icons </strong>(to display URL metrics and the number of visitors), and <strong>Image Showcase </strong>(For The Benefits use this short link).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*8HHnbDWYLxkQfeBX.png" /><figcaption>contents.blade.php</figcaption></figure><p>After we refactor our views to make them more modular. Let’s modify <em>landing.blade.php</em> as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*XVCPdr2XzRfkbLXn.png" /><figcaption><em>resources&gt;&gt;views&gt;&gt;landing.blade.php</em></figcaption></figure><p>In the code above, we extend the template that we have provided in the <em>resources&gt;&gt;layouts&gt;&gt;app.blade.php</em> file so that this page will load the required styles and the footer we have prepared. At the <em>app.blade.php</em> file, we also provide a place for content with the syntax ‘<a href="http://twitter.com/yield">@yield</a>(‘content’)’. Meanwhile at the <em>landing.blade.php</em> file, we including the ‘<em>contents.blade.php</em>’ file that we previously created.</p><p>This will be very useful when we create complex websites, where consist of headers, footers, sidebars, etc. This is where blade templating and blade directives come in handy. More complete documentation about Blade can be accessed on the following <a href="https://laravel.com/docs/9.x/blade">page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XTUBnBn69E4iItdK.png" /><figcaption>contents.blade.php</figcaption></figure><p><a href="https://laravel.com/docs/9.x/blade">Laravel - The PHP Framework For Web Artisans</a></p><p>Next, let’s try to look at the form. Let’s edit the <em>resources&gt;&gt;views&gt;&gt;layouts&gt;&gt;contents.blade.php</em> file in the MastHead section. In that code, line 9, we add <a href="http://twitter.com/csrf"><em>@csrf</em></a> which is a Blade Directive to avoid <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery"><strong>Cross-Site Request Forgery</strong></a>. We should mainly use it when accessing routes with POST, PUT, PATCH, and DELETE methods in our Laravel web. But for simplicity, in the following example, our form still uses the GET method (<strong>line 7</strong>) and points to the route we defined earlier, namely <em>‘/laravel-welcome’.</em></p><p>Let’s try to access the page, and press the button. We will be redirected to the<em> ‘laravel-welcome’</em> route. Look at the url in the web browser, something like this:</p><blockquote><em>http:// pendekin.test/laravel-welcome?</em><strong><em>_token=RBEGQ3qbiH4OgSN1W5eDCihqdizdGEmY0RQXOfYu</em></strong><em>.</em></blockquote><p>This _token variable is used in the CSRF protection above. More details about CSRF protection in Laravel can be read in the following <a href="https://laravel.com/docs/9.x/csrf">documentation</a>.</p><p><a href="https://laravel.com/docs/9.x/csrf">Laravel - The PHP Framework For Web Artisans</a></p><p>I think that’s enough for the tutorial about Models and Views. I hope it’s clear and useful for us. There are still forms but we will discuss them further together with the Controller considering they are very related.</p><p>If you feel this tutorial is helpful please share this post, clap, and follow me on Medium. Please don’t hesitate to ask in the comments if you have any questions or suggestions. See you guys on the next <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-implementation-of-controller-and-google-recaptcha-package-b307cea9ba00">posts</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2aed57a2918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Shortener URL with Laravel 9 — Part 1]]></title>
            <link>https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-part-1-e4a310afc342?source=rss-a22faaf19fb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a310afc342</guid>
            <category><![CDATA[mvc-pattern]]></category>
            <category><![CDATA[laragon]]></category>
            <category><![CDATA[laravel-development]]></category>
            <dc:creator><![CDATA[Agri Kridanto]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 16:07:56 GMT</pubDate>
            <atom:updated>2023-01-19T23:38:52.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Shortener URL with Laravel 9 — Introduction - Part 1</h3><p>Hello World, this is my very first post on Medium :).</p><p>I’m trying to create Shortener URL while Learning Laravel 9. I learned Laravel for the first time around 2016 or 2017, through Rahmat Awaluddin’s ebook, <a href="https://leanpub.com/seminggubelajarlaravel">“Seminggu Belajar Laravel”</a>. I think the book is awesome and beginner-friendly. If I’m not mistaken, the Laravel used in that tutorial is version 5.2 or 5.3.</p><p>Fast forward, as an IT staff in a state-owned company in Indonesia, where part of my job is to develop software, especially web-based. Laravel has always been my first option for developing the system. Currently, it has become one of the software development standards in our company. <br>There are several reasons why we make Laravel as our default development standard :</p><ol><li>PHP Web Framework by adhering to the concept of MVC (Model, View, Controller);</li><li>Lots of tools that make development easier &amp; faster, such as Blade Template Engine, Eloquent ORM, Artisan CLI, Commands, Jobs, Queues, etc;</li><li>Very comprehensive official documentation.</li><li>Extensive community support. Lots of packages can be used and are available for Laravel.</li></ol><p>I think to be able to follow this tutorial you need to have basic understanding of web programming such as PHP (for programming logic), HTML &amp; CSS (for display/front-end), and SQL (for the database). If you have basic skills in these three areas, it’s not too difficult to follow this tutorial. People often ask, “do I need to learn the Code Igniter (CI) framework first?”</p><p>I don’t think so. But if you’ve used CI before, the learning process should be much faster. In my opinion, it is more important to have a basic PHP programming language, especially the concept of OOP (Object Oriented Programming).</p><p>In this tutorial series, I would divide it into 4Parts. <br>Part 1 — Introduction: Setup Development Environment, MVC Pattern, and Project Structure (<strong>this blog post</strong>). <br><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918">Part 2 — Model &amp; View Implementation</a><br><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-implementation-of-controller-and-google-recaptcha-package-b307cea9ba00">Part 3 — Controller &amp; Laravel Packages</a><br><a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-deploy-on-shared-hosting-part-4-a8bfe90f1245">Part 4 — Deployment on Shared Hosting</a></p><p>The outcome of this tutorial can be accessed in <a href="https://1ln.xyz/">https://1ln.xyz</a> . If you prefer the tutorial in Bahasa, I have the very same tutorial on my <a href="https://blog.1ln.xyz/2022/12/04/pendekin-s1e00/">blog</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_i5dXOQJQ9PAhtqC.png" /><figcaption>demo project<a href="https://1ln.xyz/"> https://1ln.xyz</a></figcaption></figure><p>Without further ado, first thing first we would set up the development environment. I assume you are using the Windows operating system because it is probably the most widely used.</p><ol><li><strong>Laragon Installation</strong></li></ol><p>I would recommend using Laragon as our development environment on Windows Machine. What are the advantages of using Laragon? I think the installation is so simple and we can use it very quickly. There are some features/modules pre-installed with Laragon such as Web Server, Database, Git Version Control, Composer, etc. These features are extremely helpful for Laravel Development. In my opinion, the most useful feature is to create a virtual host so that our application can be accessed with a certain domain on our local PC, for example, <a href="http://app.test/">http://app.test</a>.</p><p><a href="https://laragon.org/">Laragon</a></p><p>For installation, just visit the download page on the web. We will use Laravel 9 here, where one of prerequisites is using PHP version 8. So we need to download the appropriate version of Laragon, which is <a href="https://objects.githubusercontent.com/github-production-release-asset-2e65be/38957562/707e5668-b8ca-4deb-9c02-6705e235f782?X-Amz-Algorithm=AWS4-HMAC-SHA256&amp;X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230116%2Fus-east-1%2Fs3%2Faws4_request&amp;X-Amz-Date=20230116T113630Z&amp;X-Amz-Expires=300&amp;X-Amz-Signature=523bdef8e95817e5359519b479cfec173dfd907f39ebc34f81b8e4a7e4e3c671&amp;X-Amz-SignedHeaders=host&amp;actor_id=8034995&amp;key_id=0&amp;repo_id=38957562&amp;response-content-disposition=attachment%3B%20filename%3Dlaragon-wamp.exe&amp;response-content-type=application%2Foctet-stream">Laragon 6</a>.</p><p>After the installation is finished, please open it. On Laragon’s main menu, we can access Laragon’s terminal (to access Git, Composer, Command Line Interface (CLI), etc). We can also access the database client, which is Heidi SQL to access our databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*MMQywlVhYuO0928m.png" /><figcaption>Laragon Main Menu</figcaption></figure><p><strong>2. Create Laravel 9 Project</strong></p><p>So, we have Laragon pre-installed with composer and git. Here we can directly clone the Laravel 9 project using the Laragon terminal with the following command. The name of the project that we will create is<strong> pendekin.</strong></p><pre>composer create-project laravel/laravel pendekin</pre><p>Here’s a preview of the Laragon’s Terminal screen when running the command above. Behind the scenes what happened was that we downloaded Laravel version 9.3.12 and its dependencies automatically. Thanks to Composer which is a dependency manager for projects with the PHP programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XxFhWtQEOtUASMZD.png" /><figcaption>Setup Laravel project and dependencies</figcaption></figure><p>Let’s try to click Start All on the Laragon Main Menu and visit the address <a href="http://pendekin.test/">http://pendekin.test</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-yYHJ9a3N_v9F_J7.png" /><figcaption>Default Page from Laravel fresh installation</figcaption></figure><p>With the auto virtual hosts setting, Laragon writes down the virtual host address on our PC. Please try going to <em>C:\Windows\System32\drivers\etc\hosts</em></p><blockquote>127.0.0.1 pendekin.test #laragon magic!</blockquote><p>If we use an application like XAMPP then we need to set up the virtual host manually. We can also access our Laravel application through the built-in Laravel web server using the “<em>php artisan serve</em>” syntax. However, according to the explanation above, we still use Laragon because there are quite a lot of features that we can use, such as composer, git, database, and the web server.</p><p><strong>3. Visual Studio Code (VS Code) Installation</strong></p><p>Visual Studio Code (VS Code) is a text editor from Microsoft which is open source and became the most popular developer option, with 70% of 82K total respondents using it (according to a<a href="https://insights.stackoverflow.com/survey/2021#section-most-popular-technologies-integrated-development-environment"> StackOverflow survey</a>). In VS Code there are many extensions that we can use for easier development process. Not only for developing applications with PHP programming languages such as Laravel but VS code can also be used to develop mobile projects, for example using Flutter, it can also be used to develop applications with Java or Python and so much many other use-cases. So, let’s download and install it.</p><p><a href="https://code.visualstudio.com/">Visual Studio Code - Build what comes next</a></p><p>Because here we will often use the Laragon terminal for development, such as accessing the Composer and Artisan CLI (Command Line Interface), <br>so we need to integrate the Laragon terminal into VS code. Press <em>Ctrl+Shift+P</em>, <em>Select Preferences: Open User Setting (JSON)</em>, and follow this gist <a href="https://gist.github.com/rachids/062dfc8200d19a04131fea5c0d4e93fa">https://gist.github.com/rachids/062dfc8200d19a04131fea5c0d4e93fa</a>. Voila, Laragon’s terminal can be accessed from your VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FqQooR5MuJOM83V7.png" /><figcaption>Integrate Laragon’s terminal into VS Code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3VrlTKZiv-Fe5C3-.png" /><figcaption>Laragon’s terminal inside VS Code</figcaption></figure><p><strong>4. Setup Git Repository</strong></p><p>We’re gonna use GitHub as the repository of our project, so Git is the version control that we use in this project. Version control is a useful when you’re working on a project with a team and it helps keep track of every change made to the code.</p><p>In addition, we will use Git to deploy this project via SSH so there is no need to copy the project from the local PC to our hosting/deployment server. The repository for this project can be accessed at <a href="https://github.com/agriirga/pendekin">https://github.com/agriirga/pendekin</a>.</p><blockquote>We would use shared hosting with SSH on Domainesia. You can use it for your hosting too &amp; <strong>you can get discount of up to 30%, valid forever. </strong>I would explain the process of eployment on this shared hosting on <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-deploy-on-shared-hosting-part-4-a8bfe90f1245">part 4 of this tutorial series</a>.</blockquote><p><a href="https://my.domainesia.com/ref.php?u=16711">DomaiNesia Jagonya Domain &amp; Web Hosting Indonesia</a></p><p><strong>5. MVC Pattern</strong></p><p>What is MVC? <strong>MVC (Model View Controller)</strong> is one of the architectural patterns of a system/application. As the name implies MVC is divided into 3 parts :</p><p>— <strong>Models (M)</strong></p><p>Models is a component that can interact with the database like perform query statements such as fetching data, adding new entries, updating existing ones, and deleting them. In Laravel, there are really handy tools like Eloquent ORM (Object Relational Mapper). We will discuss this in more detail in the next tutorial</p><p>— <strong>Views (V)</strong></p><p>Components related to the User Interface (UI) that will be presented to the user. In this MVC concept, the Presentation / UI Layer is separate from the programming logic that we use.</p><p>— <strong>Controllers</strong><br> The component whose job is to interact with requests from users. It receives requests, handles any necessary logic, and sends back responses and/or generates views for the user’s browser or application to display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*h9MvU1-QoOPvXOl2.png" /><figcaption>Laravel’s MVC Pattern</figcaption></figure><p>In Laravel’s MVC implementation, there’s one key component that plays a big role, and that’s the Router. It’s in charge of receiving user requests and figuring out what to do next. Generally speaking, the Router will determine which Controller is in charge of serving the request, but it is possible to directly access Views and or Models. The image above shows the relationship between these components.</p><p><strong>6. Laravel 9 Project / Folder Structure</strong></p><p>In the root directory, in the app folder, there are files with the .php extension used in the Controller and Model. <br> — The controller files are located in the <em>App&gt;&gt;Http&gt;&gt;Controllers</em> folder, <br> — Files for Models are in the <em>App&gt;&gt;Models</em> folder.<br> — Views, located in the <em>Resources&gt;&gt;Views</em> folder. In the resources folder, there are also css and js folders to store the assets that we use in generating the UI.</p><p>What about routers?? The router is in the routes folder. For web applications, the router settings are in the web.php file. Laravel is also a powerful framework for creating REST APIs, in that case, the router written in api.php.</p><p>Access to router is represented via the URL address accessed in our application. In the example below, we are trying to create a new route:<em> /</em><strong><em>coba_route</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-bw1uVVcs8DvkXM3.png" /><figcaption>define new route “coba-route”</figcaption></figure><p>With the same function as the previous code, it will accessing welcome views. Let’s try testing at the address: <a href="http://pendekin.test/coba-route">http://pendekin.test/coba-route</a>. Then, the very same page will appear.</p><p>Let’s back to web.php. The example shows that when our website is accessed via the URL <a href="http://pendekinin.test/coba-route">http://pendekin.test/coba-route</a>, the router will point to the ‘welcome’ view and display the default page for this project. In this example, it doesn’t pass through the Controller, so it goes directly to Views to generate the page that is displayed to the user. So it means router will generate pages that will be served to users in the resources/views<em>/welcome.blade.php file</em>.</p><pre>return view(&#39;welcome&#39;);</pre><p>Maybe you are also curious, why is the name welcome.<strong>blade.php</strong> ?? Because Laravel uses the Blade Template Engine. We’ll discuss it later in the Views implementation tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OMcXzuqLq5zUThe2.png" /><figcaption>welcome.blade.php</figcaption></figure><p>Last but not least, the Laravel project has a <strong>.env</strong> <strong>file</strong> in the root folder. <br>We can use this file to put all the configurations and credentials we need for the project. It’s great because everyone on the team can have their own settings and it’s super easy to switch between different servers. you can use it to store your database information or access credentials for other systems like email services / SMTP. When working as a team, each person can use their own database on their local machine, but when we deploy to other servers, the configurations are different.</p><p>Since the .env file contains <strong>highly confidential information, please be careful</strong>, don’t share the file with other people and don’t include the file in our repository. By default, Laravel includes a <em>.gitignore</em> file to prevent this as shown below. Further explanation about <em>.env </em>file can be read in the Laravel documentation at this<a href="https://laravel.com/docs/9.x/configuration"> link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*QhJHJyePzlx9H8zO.png" /><figcaption>.gitignore</figcaption></figure><p>Great Job! We’ve prepared the project development environment, cloned Laravel project, access virtual host, set up vs code &amp; git repository, and learn the MVC concept of Laravel. <strong>If you’re feeling a little overwhelmed by some of the terms like Git, Composer, Database Client, etc, don’t worry</strong>! You can learn more about them later.</p><p>If you feel this tutorial is helpful please share this post, claps, and follow me on Medium. Please don’t hesitate to ask in the comments section if you have any questions or suggestions. See you guys on the next <a href="https://medium.com/@agri.kridanto/build-shortener-url-with-laravel-9-model-view-implementation-part-2-f2aed57a2918">posts</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a310afc342" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>