<?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 Hendrik Setiawan on Medium]]></title>
        <description><![CDATA[Stories by Hendrik Setiawan on Medium]]></description>
        <link>https://medium.com/@hendriks96?source=rss-8d85c8a920d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z0EsuhjKxjUg8WSS_mgKGg.jpeg</url>
            <title>Stories by Hendrik Setiawan on Medium</title>
            <link>https://medium.com/@hendriks96?source=rss-8d85c8a920d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:11:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hendriks96/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[Access the localhost url to become a public url]]></title>
            <link>https://medium.com/@hendriks96/access-the-localhost-url-to-become-a-public-url-959086dd0dbd?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/959086dd0dbd</guid>
            <category><![CDATA[ngrok]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 11:02:29 GMT</pubDate>
            <atom:updated>2024-06-08T11:02:29.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tGqcll89t5Hcibpt" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever accessed localhost with an internet network. If not, then you must read and understand the following tutorial. When developing our application we will have a lot to do with API. Data sources are stored in a database, processed via a server and then distributed via an API, for example the REST API. To access the API we need a local network or internet. Apart from that, we need an IP address as identity when connected to a network.<br>When we develop applications, for example mobile applications, we need a network as a link between the API and the application. If we develop a website, this is not a problem, we can directly call the api using a local network that can be accessed by the client itself. However, try to access the website via the “internet network” or a network outside the local network, for example accessing via another computer or accessing via phone. There is a problem, unless we connect our device to the same network / local network, then we can access the website. So, how to make the website accessible using the internet / non-local network, we can use a tool called “ngrok”.</p><p>Ngrok is a tool that can connect external networks in a consistent, secure, and repeatable way without requiring any changes to the network configuration. With this tool we can also change local network access to be accessible by external networks. This is useful for us if we want to access an API/website using another device that is not connected to our network. Or useful when presenting to users the results of our work.</p><p>Before starting this tutorial, I will create a simple REST API that I will access using the internet network. Create a new folder called “my-rest-api” in htdocs, here I will use xampp as the web server, then create a new file called “index.php”.</p><figure><img alt="my-rest-api path" src="https://cdn-images-1.medium.com/max/1024/0*xYdUVbnCifh9cQXQ" /><figcaption>Picture 1.1 my-rest-api path</figcaption></figure><p>Add the following php script, here we will use the basic php script. When the user accesses the my-rest-api url, it will display a response in json form.</p><pre>&lt;?php<br>    $response   =   [<br>        &#39;sucess&#39;    =&gt;  true,<br>        &#39;message&#39;   =&gt;  &#39;if you can see this message, your api success&#39;<br>    ];<br>    echo json_encode($response, JSON_PRETTY_PRINT);<br>?&gt;</pre><p>In the json response we will display ‘success’ with the value true, and ‘message’ as a message if the user has successfully called the url.<br>Call “index.php” in the browser. Here, because I use xampp, I just write <a href="http://localhost/my-rest-api">http://localhost/my-rest-api</a>.</p><figure><img alt="response json success" src="https://cdn-images-1.medium.com/max/826/0*Xl6v98WFbGSzO6Il" /><figcaption>Picture 1.2 response json success</figcaption></figure><p>The URL has been created, now try to access the URL via another device connected to the internet network. definitely can’t, right ? API cannot be accessed, to access the API try connecting a network connection to a local network. Here I do a hotspot from the PC, so the phone device will connect to the PC via the hotspot. Now we will use the PC as the server and the phone will be the client.</p><p>Open cmd first on the computer that will be used as a server, then type “ipconfig”. To access the api we need an IP address which will be used as the address to call the api that has been created.</p><figure><img alt="information ip address" src="https://cdn-images-1.medium.com/max/623/0*_CGI_nOyUSC7bKBG" /><figcaption>Picture 1.3 information ip address</figcaption></figure><p>We will use the IPv4 address. The IP address above will act as the URL.<br>Copy the IPv4 above then access the url <a href="http://your-api-address/my-rest-api/">http://your-api-address/my-rest-api/</a> (change “your-api-address” with the IP of the PC that is the server) using a device that is connected to the local network.</p><figure><img alt="response json success called another device" src="https://cdn-images-1.medium.com/max/576/0*2v7t1YlYHlUtZL0q" /><figcaption>Picture 1.5 response json success called another device</figcaption></figure><p>If it appears as in the example image above, then our URL address has been successfully accessed using the local network, now try to deactivate the hotspot or decide not to use the network then access the URL again. Now we are not accessing because the network connection from the client and server has been lost.</p><p>This is where we can use ngrok. Ngrok allows us to still access a PC that has been used as a server even though it is not on a local network.</p><p>Ngrok will help with forwarding from localhost to public URL so, we can call the my-rest-api even though it is not on the same network.</p><p>Because we are still learning, we will use the free version of Ngrok. For the price of ngrok, you can see it <a href="https://ngrok.com/pricing">here</a>.</p><p><strong>Register ngrok</strong></p><p>Open the ngrok site at <a href="https://ngrok.com/">ngrok.com</a>, if you have already registered, you can skip the following steps, if not you can click sign up and you will be directed to the new user registration page.</p><figure><img alt="first step sign up ngrok" src="https://cdn-images-1.medium.com/max/1024/0*gLfHgZgGC27EWD3A" /><figcaption>Picture 2.1 first step sign up ngrok</figcaption></figure><p>Complete the form above, then click sign up so that a verification email appears and verify the email first.<br>If multi-factor authentication information appears, click skip first. We can activate it later if we have successfully registered.<br>Next, complete the form according to your needs and profession.</p><figure><img alt="second step sign up ngrok" src="https://cdn-images-1.medium.com/max/1024/0*PuKd9oxURgg-pgqP" /><figcaption>Pictre 2.2 second step sign up ngrok</figcaption></figure><p>In the option “are you using ngrok for ?”, select development then click“ continue” to continue the registration process.</p><figure><img alt="select using ngrok" src="https://cdn-images-1.medium.com/max/577/0*FGBJgjjZHJNtQtCz" /><figcaption>Picture 2.3 select using ngrok</figcaption></figure><p>If successful, you will be taken to the get-started page along with how to install ngrok based on the operating system used.</p><figure><img alt="welcome page ngrok" src="https://cdn-images-1.medium.com/max/1024/0*3kzQx6TjbRLM3XgO" /><figcaption>Picture 2.4 welcome page ngrok</figcaption></figure><p>You can follow the installation guide provided, adjusting it to the operating system you are using. Because I use Windows, I will explain the installation using Windows in the following tutorial.<br>On Windows there are two ways that can be used to install, using chocolatey or using the .exe setup file. If you use chocolatey then you need to install chocolatey first, we will use the second method, by using the .exe setup file.</p><p>Scroll down the setup page, and move to the download tab to find the exe file.</p><figure><img alt="download exe file" src="https://cdn-images-1.medium.com/max/1003/0*6hX_CJj1VNeVkNH2" /><figcaption>Picture 2.5 download exe file</figcaption></figure><p>Download the exe file according to the operating system used. Extract the file and we will find the exe file. Move the “ngrok.exe” file to the path “C:\Windows\System32”.</p><figure><img alt="move ngrok to system windows" src="https://cdn-images-1.medium.com/max/1024/0*pM5JvmQu3_0g5wiB" /><figcaption>Picture 2.6 move ngrok to system windows</figcaption></figure><p>Add the path “C:\Windows\System32\ngrok.exe” to the system environment variable like this.</p><figure><img alt="update environment variable" src="https://cdn-images-1.medium.com/max/681/0*Kq0NW7Z-dD3dc6fJ" /><figcaption>Picture 2.7 update environment variable</figcaption></figure><p>When everything is finished, open the command prompt in Windows. We will run the ngrok version command to find out whether ngrok has been successfully added.</p><figure><img alt="check version ngrok" src="https://cdn-images-1.medium.com/max/734/0*w_ECeSzf3SDd0DAw" /><figcaption>Picture 2.8 check version ngrok</figcaption></figure><p>As seen in the picture, cmd displays the ngrok version when ngrok version is run. If the ngrok version appears then ngrok was added successfully.</p><p>On the setup page, if we scroll down we will find the token that will be used for user authentication.</p><figure><img alt="find auth token ngrok" src="https://cdn-images-1.medium.com/max/875/0*Z0mgrghWnbnkPvnZ" /><figcaption>Picture 2.9 find auth token ngrok</figcaption></figure><p>Copy the code and paste it in the command prompt.</p><figure><img alt="auth token success added configuration" src="https://cdn-images-1.medium.com/max/1000/1*XrB8BWuJmVg7LVMmoBC5kw.png" /><figcaption>Picture 2.10 auth token success added configuration</figcaption></figure><p>If a message like the image above, appears then the auth token has been added successfully.</p><p>To start running ngrok type the command “ngrok http 80” or “ngrok http http://localhost:8000”</p><figure><img alt="ngrok is running" src="https://cdn-images-1.medium.com/max/953/1*XsY6zyGgLxg0WlBJ2cb_fg.png" /><figcaption>Picture 2.11 ngrok is running</figcaption></figure><p>Ngrok is running successfully, try to access the URL in the forwarding</p><figure><img alt="access web server using ngrok" src="https://cdn-images-1.medium.com/max/1024/0*hKJquTkoFAlJRXsp" /><figcaption>Picture 2.12 access web server using ngrok</figcaption></figure><p>We have successfully created our public web server, try to access my-rest-api, the api that was previously created.</p><figure><img alt="response json using ngrok" src="https://cdn-images-1.medium.com/max/751/0*1dJdwLJd_WK0018z" /><figcaption>Picture 2.13 response json using ngrok</figcaption></figure><p>Nice, now API is running as desired. Try accessing via another device or phone on a different network.</p><figure><img alt="response json in another device using ngrok" src="https://cdn-images-1.medium.com/max/1024/0*qXc9XujrMG9XzChH" /><figcaption>Picture 2.14 response json in another device using ngrok</figcaption></figure><p>Now we have succeeded in accessing API via the internet network. With this, we can develop applications without having to be limited by an internet network connection. For more details, you can read the documentation <a href="https://ngrok.com/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959086dd0dbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blade templating laravel]]></title>
            <link>https://medium.com/@hendriks96/blade-templating-laravel-6db9618ad83a?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db9618ad83a</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Thu, 30 May 2024 16:55:39 GMT</pubDate>
            <atom:updated>2024-05-30T16:55:39.720Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcYRy7Y02lbENLTNqf9Lhw.png" /></figure><p>Have you ever created a website appearance without using a framework. When building a website, we usually use HTML, CSS and JavaScript. 3 basic parts for creating a website. All these parts are combined into one html file or three files (html, css, js) which are loaded on one html page so that it becomes an attractive website.</p><p>It doesn’t matter if the website you are building only has one page, but imagine if the website you are building is very complex, for example a project website for administrators. A website that has many features and many menus. If we only use one HTML file for one feature, it will certainly be very inefficient for websites that have many features.</p><p>In Laravel, we can make the appearance of the website easy to manage well and efficiently. If we build a website that is very large and has many features, the Laravel “blade” is very helpful.</p><blockquote>Quoted from the Laravel documentation, “blade” is a simple but powerful templating engine included with Laravel. Unlike some PHP templating engines, Blade doesn’t limit you to using plain PHP code in your templates.<br>You can read about Laravel Blade in the following <a href="https://laravel.com/docs/11.x/blade#introduction">link</a>.</blockquote><p><strong>Preparation</strong></p><p>Before starting this tutorial, we will use an html file from “codingnepal”, you can download it <a href="https://www.codingnepalweb.com/animated-sidebar-menu-using-only-html-css/">here</a>.</p><p>Extract the file that has been downloaded and there will be “index.html” and “style.css” files. If the html file is loaded then the results will be like the following.</p><figure><img alt="index.html file open" src="https://cdn-images-1.medium.com/max/1024/0*10IBYTD31_7gCKJo" /><figcaption>Picture 1.1 index.html file open</figcaption></figure><p>We assume that we have installed and created Laravel project on our PC. If you haven’t yet, see the post <a href="https://medium.com/@hendriks96/how-to-install-laravel-on-pc-60c39cc7f418">here</a>.</p><p><strong>Start training</strong></p><p>First, move the “style.css” file into the public folder in the Laravel project.</p><figure><img alt="File style.css inside public" src="https://cdn-images-1.medium.com/max/464/0*qM40MfhSuAnKWhn-" /><figcaption>Picture 2.1 File style.css inside public</figcaption></figure><p>Create a file in the “application.blade.php” file in the views folder (resources/views) then open the “index.html” file using a text editor and move it to “application.blade.php”.</p><figure><img alt="application.blade.php file" src="https://cdn-images-1.medium.com/max/1024/0*VmyUy7ltHbadCaQB" /><figcaption>Picture 2.2 application.blade.php file</figcaption></figure><p>Open “ web.php” inside app/routes/web.php and add the following code :</p><pre>Route::get(&#39;dashboard&#39;, function(){<br>    return view(&#39;application&#39;);<br>});</pre><p>The code above functions as the dashboard page address. Run laravel by typing the command</p><pre>php artisan serve</pre><p>Then open the page <a href="http://127.0.0.1:8000/dashboard">http://127.0.0.1:8000/dashboard</a>. The same page will appear as before</p><figure><img alt="dashboard empty content" src="https://cdn-images-1.medium.com/max/1024/0*HY_BLRrNX5y35Bk6" /><figcaption>Picture 2.3 dashboard page with empty content</figcaption></figure><p>Create a new file in the views folder, we will name it “dashboard.blade.php”. this will be the dashboard page<br>open “style.css” add the following code as a style for the content</p><pre>.content{<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  height: 200px;<br>}</pre><p>Oopen the “application.blade.php” page again, add the following code between the tags “&lt;body&gt;&lt;/body&gt;”</p><pre>&lt;div class=&quot;content&quot;&gt;<br>    @yield(&#39;content&#39;)<br>&lt;/div&gt;</pre><p>We will display a simple page on the dashboard. We will write a dashboard page on that page.<br>Reopen the “dashboard.blade.php” page that was created earlier then add the following code :</p><pre>@extends(&#39;application&#39;)<br>@section(&#39;content&#39;)<br>    &lt;h3 style=&quot;&quot;&gt;Dahsboard page&lt;/h3&gt;<br>@endsection</pre><p>Iin the code above, the dashboard page inherits the application extends(‘application’) page, then we will inject the contents of the page into the application via the key “content” on section(‘content’) and receive it on the application page via yield(‘content’).</p><p>Now reopen the “web.php” page. In the routes dashboard, change it to the following</p><pre>Route::get(&#39;dashboard&#39;, function(){<br>    return view(&#39;dashboard&#39;);<br>});</pre><p>Then try to refresh the page again</p><figure><img alt="dashboard page with content" src="https://cdn-images-1.medium.com/max/1024/0*VdFso-K69mIJy-7f" /><figcaption>Picture 2.4 dashboard page with content</figcaption></figure><p>We can see that there is no change between before and after using blade templating. You can only see the words dashboard page in the middle of the page.</p><p>Now try to reopen the “application.blade.php” page, we see that the sidebar is still attached to its parent, namely in the application. To make it more structured and neat, we will separate the sidebar from the application page.</p><p><strong>Modify sidebar to make it reusable</strong></p><p>Create one file in the views folder named “sidebar.blade.php”. Then move the sidebar section which is located between &lt;div class=’sidebar’&gt;&lt;/div&gt; into the “sidebar.blade.php” file, so that sidebar.blade.php becomes like this</p><figure><img alt="sidebar file" src="https://cdn-images-1.medium.com/max/859/0*pPTbEOLGYyTQgzDX" /><figcaption>Picture 2.5 sidebar file</figcaption></figure><p>In “application.blade.php” add code @inclue(&#39;sidebar&#39;) above the tag &lt;div class=”content”&gt; or left behind by the previous sidebar code<br>This function is to call sidebar resources located in the views folder.</p><figure><img alt="application blade with sidebar and content" src="https://cdn-images-1.medium.com/max/841/0*z8TU5528T2QOia77" /><figcaption>Picture 3.2 application blade with sidebar and content</figcaption></figure><p>Then try to refresh the web page earlier. If it still runs as before it means there is no error. Even though there is no difference, our code actually becomes more structured.</p><p>In Picture 3.2 you can see that the page title (see inside the &lt;title&gt; tag) has not changed at this time “Responsive Sidebar Menu”. Delete the text and change it to</p><pre>&lt;title&gt;@yield(&#39;title&#39;, &#39;My Menu&#39;)&lt;/title&gt;</pre><p>Refresh the page and see that the page has now changed its title to “My Menu”</p><figure><img alt="title changed to my menu" src="https://cdn-images-1.medium.com/max/1024/0*xKZawB2xd2JgtmgY" /><figcaption>Picture 3.3 title changed to my menu</figcaption></figure><p>On the code @yield(‘title’, ‘My Menu’), the first parameter is the key and the second parameter is the default value, which means that if no value is injected, the default value will be displayed.<br>Go back to the “dashboard.blade.php” page. then add the following code above the content section</p><pre>@section(&#39;title&#39;, &#39;dashboard&#39;);</pre><p>Refresh the dashboard page again and see that the page title has changed to Dashboard.</p><figure><img alt="title changed to dashboard" src="https://cdn-images-1.medium.com/max/1024/0*pzFHG9MsJ3KiqCUu" /><figcaption>Picture 3.4 title changed to dashboard</figcaption></figure><p>We have used two “sections”, the first is “title” and the second is “content”. If we see that the “content” section has an “end section” closing, but the “title” section does not have a closing. This is because in the first section the data that is injected is in the form of a “string”, which is different from the second section because the data that is injected is in the form of an “html” tag. So it needs to be enclosed with a “section” and “end section”.</p><figure><img alt="title and content section" src="https://cdn-images-1.medium.com/max/701/0*kHsF_3TnysWj9SGN" /><figcaption>Picture 3.5 title and content section</figcaption></figure><p>Next, we will try to create a “shortcut” page, where this page will be in the “shortcut” menu.<br>When the sidebar shortcut is pressed we will move it to the shortcut page, then we will change color the shortcut label to red so that it appears that the shortcut page is active. Create a file called “shortcuts.blade.php” in the views folder then copy and paste the code from “dashboard.blade.php”</p><pre>@extends(&#39;application&#39;)<br><br>@section(&#39;title&#39;, &#39;Shortcuts&#39;)<br>    <br>@section(&#39;content&#39;)<br>    &lt;h3 style=&quot;&quot;&gt;Shortcuts page&lt;/h3&gt; <br>@endsection</pre><p>To see the difference, here we will change the word “dashboard” to “shortcuts” like the code above.<br>back to the “web.php” page, add a new route on the “web.php” page called shortcuts.</p><pre>Route::get(&#39;shortcuts&#39;, function(){<br>    return view(&#39;shortcuts&#39;);<br>});</pre><p>Save it and try to access the shortcuts page on <a href="http://127.0.0.1/shortcuts">http://127.0.0.1/shortcut</a>s</p><figure><img alt="shortcuts page" src="https://cdn-images-1.medium.com/max/1024/0*Cq06h8kcTyDqSsy3" /><figcaption>Picture 3.6 shortcuts page</figcaption></figure><p>Now we have access to the shortcuts page, as you can see that the title and page lead to shortcuts. but the color on the sidebar doesn’t direct to the shortcuts menu. let’s fix it.<br>First try to fix the route. Add a value to pass to the shortcuts page.</p><pre>Route::get(&#39;shortcuts&#39;, function(){<br>    return view(&#39;shortcuts&#39;, [&#39;menu&#39; =&gt; &#39;shortcuts&#39;]);<br>});</pre><p>The code above will send data using the “menu” key and “shortcuts” values. We will check if the menu is the same as the shortcuts then it will activate the shortcuts menu. Reopen the “sidebar.blade.php” file, add the checking condition class to the “a” tag.</p><pre>&lt;a href=&quot;shortcuts&quot; class=&quot;{{$menu == &#39;shortcuts&#39; ? &#39;active&#39; : &#39;&#39;}}&quot;&gt;</pre><p>In the code above uses a ternary operator which will check the variables that we send via routes. If it is appropriate then it will add an active class, if it fails the class will be empty. Try pressing refresh again and see the results.</p><figure><img alt="shortcuts menu active" src="https://cdn-images-1.medium.com/max/1024/0*UfsEfyqwF3dMB14F" /><figcaption>Picture 3.7 shortcuts menu active</figcaption></figure><p><strong>Make sidebar user friendly</strong></p><p>The shortcuts are red but the dashboard is also red. To eliminate passing data to dashboard routes that have dashboard values.</p><pre>Route::get(&#39;dashboard&#39;, function(){<br>    return view(&#39;dashboard&#39;,[&#39;menu&#39; =&gt; &#39;dashboard&#39;]);<br>});</pre><p>Don’t forget to add the same code to the “a” tag</p><pre>&lt;a href=&quot;dashboard&quot; class=&quot;{{$menu == &#39;dashboard&#39; ? &#39;active&#39; : &#39;&#39;}}&quot;&gt;</pre><p>Now the code on the sidebar page will be like this</p><figure><img alt="code inside sidebar menu" src="https://cdn-images-1.medium.com/max/695/1*Pli7YSbNQtzSSf2kijlOLg.png" /><figcaption>Picture 4.1 code inside sidebar menu</figcaption></figure><p>Save and try to refresh the page. Currently, if we click on the dashboard or shortcuts or vice versa, it should be safe.</p><figure><img alt="result of shortcuts page" src="https://cdn-images-1.medium.com/max/1005/0*CR7ce7IjdAcuQBE_" /><figcaption>Picture 4.2 result of shortcuts page</figcaption></figure><p>Next, to deepen the blade, try continuing to create the next menu and page. To understand more about blade templating, we can read the documentation at <a href="https://laravel.com/docs/11.x/blade">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPVIb8TtRU-s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPVIb8TtRU-s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPVIb8TtRU-s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/102bcd26fcbc1e33fcb5d8488dd9da73/href">https://medium.com/media/102bcd26fcbc1e33fcb5d8488dd9da73/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db9618ad83a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database migration in laravel]]></title>
            <link>https://medium.com/@hendriks96/database-migration-in-laravel-9a094ca933b7?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a094ca933b7</guid>
            <category><![CDATA[website-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel-migrations]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Sat, 18 May 2024 05:12:09 GMT</pubDate>
            <atom:updated>2024-05-18T05:12:09.290Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89loQ8YjlWJP60A6OjLJ6g.png" /></figure><p>When we create a complex website, we always use a database. With a database we can manage and store data or information easily. MySQL is a database that is often used by developers and is relational in nature and is displayed in table form. To process data in a database, we have to create a database and then create tables. It will be very troublesome if you have to create lots of tables and it will take time to share them with the team.</p><p>If we create a website using Laravel, we know database migration. A version control for databases that allows your team and you to share database schema definitions across applications.</p><p>Laravel Schema facade provides support for creating and manipulating tables. Usually, this façade is used to create and modify tables and columns in the database.</p><p><strong>Introduction</strong></p><p>When we create a Laravel project via Composer, 4 database migration scripts will automatically be created, including creating the users table, password resets, failed_jobs, personal_access_tokens. We can use these tables to store user data or to hold temporary tokens. These 4 files can be seen in the migration database. You can find this file inside database/migrations directory.</p><figure><img alt="List of migration file" src="https://cdn-images-1.medium.com/max/940/1*cQ7IFpCerqYeCGK-CrcjDg.png" /><figcaption>Picture 1.1 Default file migrations inside migrations directory</figcaption></figure><p>Before run migrations, we make sure there is MySQL on the local computer. Create a database called “laravel_migration”. And change the database settings in the “.env” file like this.</p><figure><img alt="database env file" src="https://cdn-images-1.medium.com/max/563/1*CftP8e3bRg8u4hHAOcbG6g.png" /><figcaption>Picture 1.2 Env configuration</figcaption></figure><p>Run the following command to execute the migration script.</p><pre>php artisan migrate</pre><figure><img alt="running migrations success" src="https://cdn-images-1.medium.com/max/940/1*QEd_-rUgF6__WfauQoZRhg.png" /><figcaption>Picture 1.3 Running migrations success</figcaption></figure><p>To ensure the migration is complete, we can check the “laravel_migration” database.</p><figure><img alt="table after running migrations" src="https://cdn-images-1.medium.com/max/940/1*0mf-B37u3ojF84qakqyMhw.png" /><figcaption>Picture 1.4 Table after running migrations</figcaption></figure><p>Great, now we have successfully executed the migration. If we look at 1 migration script it will create 1 table in the database. Previously there were 4 migration scripts, why were there 5 tables created?</p><p>Let’s to try opening the “migrations” table.</p><figure><img alt="Migration file after running artisan" src="https://cdn-images-1.medium.com/max/940/1*9P0KXn9yVB6ClFlZRrYirg.png" /><figcaption>Picture 1.5 Migrations data inside table</figcaption></figure><p>There are 3 columns that are automatically filled in when we run migration. Yes, this migration table will become history when we run the migration script.</p><p>By default the PHP files in the “migrations” folder can be run once. This does not apply if we run command again and no changes to the “migrations” folder. As an example let’s run the command</p><pre>php artisan migrate</pre><figure><img alt="running command migration" src="https://cdn-images-1.medium.com/max/940/1*oNEak7UE2fWLB9vQNgnueQ.png" /><figcaption>Picture 1.6 Running command migration</figcaption></figure><p>You can see the information that there is nothing to migrate information, which means no migration has been executed.</p><p>To make the migration executable again, try deleting one of the data in the migration table. For example I will delete the users table.</p><figure><img alt="removed users table history" src="https://cdn-images-1.medium.com/max/802/1*NNZzfiqvQX71CHaTr6yFwg.png" /><figcaption>Picture 1.7 Removed users table history</figcaption></figure><p>Then run the “php artisan migrate” script again. Oops, there was an error.</p><figure><img alt="error while running artisan script" src="https://cdn-images-1.medium.com/max/940/1*fZ5xKba9r-QDsAH6FJ0iWw.png" /><figcaption>Picture 1.8 Error while running artisan script</figcaption></figure><p>This is because we have created the users table before so an error occurred. Try deleting the users table from the database, or you can add a script</p><pre>Schema::dropIfExists(&#39;users&#39;);</pre><p>In the create_users_table.php file in the up function which is in the migrations folder.</p><figure><img alt="add schema drop table" src="https://cdn-images-1.medium.com/max/940/1*eApYq62Pu9PXetPVpt7cVQ.png" /><figcaption>Picture 1.9 Add schema drop table</figcaption></figure><p>Try running “php artisan migrate” again.</p><p>Great, now we’ve recreated the table from scratch. Please remember that only migration files that have not been recorded in the migrations table will be executed. In the example above, Artisan will only run 1 migrations file, namely create_users_table.php because we have deleted that file from the migrations table.</p><p><em>NB: be careful if you want to recreate the table, it’s best to “backup” first before recreating it.</em></p><p><em>Tip: Remove the Schema::dropIfExists(‘users’); when it is no longer used</em></p><p>Then, if you have a question, what if you want to insert 1 column in a table without having to create a table from scratch, we will discuss it below.</p><p><strong>Create a migration</strong></p><p>We will try to create a students table using the migration database, where there are columns id, registration_number, and name.</p><p>To create a migration, we can use the Artisan:migration command.</p><pre>php artisan make:migration create_students_table</pre><figure><img alt="student table" src="https://cdn-images-1.medium.com/max/908/1*n3wg2hpJclQJExI7dCd7cw.png" /><figcaption>Picture 1.10 Created students table</figcaption></figure><p>Open the file 2024_01_31_150725_create_students_table.php.<br>In the “up” function, add code like the following. Function “up” is the main function that will be executed when we run the php artisan migrate script.</p><pre>public function up()<br>{<br>    Schema::create(&#39;students&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;integer(&#39;registration_number&#39;);<br>        $table-&gt;string(&#39;name&#39;, 255);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><p>The code above will create a students table and columns id, registration_number, name. Meanwhile, to define columns, you can use the format blueprint-&gt;column type (column name). For other column types, you can see here <a href="https://laravel.com/docs/10.x/migrations#available-column-types">https://laravel.com/docs/10.x/migrations#available-column-types</a>.</p><p>Then run the php artisan migrate command again.</p><figure><img alt="success running migrations" src="https://cdn-images-1.medium.com/max/940/1*bdO_zURIeP9Rb4wKMCSuRQ.png" /><figcaption>Picture 1.11 Success running migrations</figcaption></figure><p>If successful, check the table in the database that we created earlier.</p><figure><img alt="table students" src="https://cdn-images-1.medium.com/max/940/1*6qCR0g40NiGulmd5_9I10w.png" /><figcaption>Picture 1.12 Students table</figcaption></figure><p>Now the students table has been successfully created, if we look at the migrations table it will add 1 migration data.</p><p><strong>Running specific migration</strong></p><p>Imagine we are working with a friend on the same project, then friend creates a migration file that has not been executed because he is still unsure about the table structure. Then we want to run our migration file because it meets our needs. Then, how do we run it, if we use the “php artisan migrate” command it will execute migration files that have not been executed.<br>We can perform even more specific migrations. We will run our own migration file. To run it we can use the command</p><pre>php artisan migrate - path=/database/migrations/full_migration_file_name_migration.php</pre><p>for example, we have created a migrations file to create the teachers table.</p><figure><img alt="structure teachers table" src="https://cdn-images-1.medium.com/max/940/1*ZNAhm_p9DaJq28REhUSeXQ.png" /><figcaption>Picture 1.12 Structure teachers table</figcaption></figure><p>So to run it just use the command</p><pre>php artisan migrate --path=/database/migrations/2024_02_25_154340_create_teachers_table.php</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*hsYNOf4YWHvJ-9H4JpwH4g.png" /><figcaption>Picture 1.13 Running migration successfully</figcaption></figure><p>Good, we have successfully created 1 table using database migrations.</p><p><strong>Add new column</strong></p><p>Then what if we need a new column. For example, we will try adding the date_of_birth column to the students table. Create a new migration using the terminal.</p><pre>php artisan make:migration add_date_of_birth_students –table=students</pre><p>in the up function add the following schema to add the date_of_birth column.</p><figure><img alt="Add schema inside migrations" src="https://cdn-images-1.medium.com/max/609/1*4bo4nLCDIdc9AT34MhBIZw.png" /><figcaption>Picture 1.14 Add schema inside migrations</figcaption></figure><p>Run the php artisan migrate command again.</p><p>Then a column named “date_of_birth” with data type date was successfully added.</p><figure><img alt="Result after run add column migrations" src="https://cdn-images-1.medium.com/max/681/1*rtmluNLeLmCsaqBgphlXrQ.png" /><figcaption>Picture 1.15 Result after run add column migrations</figcaption></figure><p>We see that the date_of_birth column will be added to the very last column, What if we want to create it in the second or third column. We’ll discuss it at the next opportunity. You can read more about database migrations in the documentation laravel here <a href="https://laravel.com/docs/11.x/migrations">https://laravel.com/docs/11.x/migrations</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a094ca933b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Api Authenticate : How to authenticate api using laravel sanctum]]></title>
            <link>https://medium.com/@hendriks96/api-authenticate-how-to-authenticate-api-using-laravel-sanctum-c4eeaa99b472?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4eeaa99b472</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 08:19:28 GMT</pubDate>
            <atom:updated>2024-01-24T08:19:28.190Z</atom:updated>
            <content:encoded><![CDATA[<h3>Api Authenticate : How to authenticate api using laravel sanctum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enSkT2ZdUB7O9yk64agK1w.png" /></figure><p>The latest version of Laravel offers the latest authentication feature, Laravel Sanctum. A simple authentication that can be used in SPA (single page application), mobile applications, and token based APIS. Quoted from laravel documentation ”<a href="https://github.com/laravel/sanctum">Laravel Sanctum</a> provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform”.</p><p>Here I will not explain more about Laravel Sanctum, its advantages or disadvantages, but I will explain the basic implementation of using Laravel Sanctum in Laravel projects. For information regarding the explanation of Laravel Sanctum, you can see the documentation directly at <a href="https://laravel.com/docs/10.x/sanctum#main-content">here</a>.</p><p><strong>Introduction</strong></p><p>Before starting, prepare the tools below to support project creation</p><ul><li>Code editor, visual studio code, sublime text, Intellij, or etc..</li><li>mysql</li><li>Composer</li><li>Postman</li></ul><p><strong>Installation</strong></p><p>Install the Laravel project using composer, run the following command in the terminal</p><pre>composer create-project –prefer-dist laravel/laravel sanctum-example</pre><p>Wait until the project creation process is complete. Then open project using code editor.</p><p><strong>Setup database</strong></p><p>Create a new database with the name “sanctum_example” in phpMyAdmin. Then open the .env file in the laravel sanctum-example project. Set up the database as follows :</p><pre>DB_CONNECTION=mysql<br>DB_HOST=127.0.0.1<br>DB_PORT=3306<br>DB_DATABASE=sanctum_example<br>DB_USERNAME=root<br>DB_PASSWORD=</pre><p>Run a new terminal in visual studio code. Terminal -&gt; New terminal (ctrl + shift + ‘). Then type the command :</p><pre>php artisan migrate</pre><p>This command will run the migration command in Laravel and will automatically create a table in the database.</p><p>If successful, there will be a table in MySQL which was generated from the Laravel migration database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HgURMMGtzhsJOfadk0G9RQ.png" /><figcaption>default table user</figcaption></figure><p><strong>Setup Laravel Sanctum Package</strong></p><p>In Laravel version 9 and above, Laravel Sanctum is automatically installed when we create a Laravel project. We can check via the composer.json file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*MeWY60TPP0NBVxJbWsjclA.png" /><figcaption>composer.json</figcaption></figure><p>If it doesn’t exist yet, you can install it via command</p><pre>composer require laravel/sanctum</pre><p>Then we publish the Laravel Sanctum configuration with the command</p><pre>php artisan vendor:publish –provider=”Laravel\Sanctum\SanctumServiceProvider”</pre><p><strong>Setup Controller</strong></p><p>Create a new controller using the command</p><pre>php artisan make:controller Api/AuthController</pre><p>Next, open the AuthController.php file in app\http\controllers\api.</p><p>Create 3 function in AuthController.php, register, login and logout</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*08aku4P8kSm-atLECS2Ugg.png" /><figcaption>function in authcontroller.php</figcaption></figure><p><strong>Register</strong></p><p>We will create a simple registration, in this example we will create a user registration using name, email and password. We will create the following use case :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ZsvW6ObH-epnNvRYF_W8OQ.png" /><figcaption>register use case</figcaption></figure><p>In the register function, add code to validate the form submitted by the user. Add the following code</p><pre>$validator = Validator::make($request-&gt;all(), [<br>                &#39;name&#39;      =&gt; &#39;required|string|max:255&#39;,<br>                &#39;email&#39;     =&gt; &#39;required|string|max:255|unique:users&#39;,<br>                &#39;password&#39;  =&gt; &#39;required|string&#39;<br>              ]);<br><br>if ($validator-&gt;fails()) {<br>  return response()-&gt;json($validator-&gt;errors());<br>}</pre><p>Next, add code to save user data if the form submitted is valid.</p><pre>$user = User::create([<br>            &#39;name&#39;      =&gt; $request-&gt;name,<br>            &#39;email&#39;     =&gt; $request-&gt;email,<br>            &#39;password&#39;  =&gt; Hash::make($request-&gt;password)<br>        ]);<br><br>$token = $user-&gt;createToken(&#39;auth_token&#39;)-&gt;plainTextToken;<br>return response()-&gt;json([<br>    &#39;data&#39;          =&gt; $user,<br>    &#39;access_token&#39;  =&gt; $token,<br>    &#39;token_type&#39;    =&gt; &#39;Bearer&#39;<br>]);</pre><p>The code above will save user data into the database and generate a token, we will send the token to the user.</p><p>Don’t forget to import the controller.</p><pre>use App\Models\User;<br>use Illuminate\Support\Facades\Hash;<br>use Illuminate\Support\Facades\Validator;</pre><p>Next we will set api routes, open api.php in app\routes\api.php and add the following code :</p><pre>Route::post(&#39;/register&#39;, [AuthController::class, &#39;register&#39;]);</pre><p>Don’t forget to import the authcontroller class file</p><pre>use App\Http\Controllers\Api\AuthController;</pre><p>Then, run laravel server using artisan</p><pre>php artisan serve</pre><p>Open postman, and run api url</p><p>Method: POST</p><p>URL : <a href="http://127.0.0.1:8000/api/registe">http://127.0.0.1:8000/api/registe</a>r</p><p>Headers: Accept: application/json</p><p>Body: name,email,password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*BwUa0papXvt4aC5UjMIFaw.png" /><figcaption>post register user</figcaption></figure><p><strong>Login</strong></p><p>Next we will create a login api that we can use to authenticate users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*_T14DpugCsxSOiKbaXEwuQ.png" /><figcaption>login use case</figcaption></figure><p>We will create a use case like the one above, almost the same as when we created the api register. Add code to validate email and password data.</p><pre>$validator = Validator::make($request-&gt;all(), [<br>                &#39;email&#39;     =&gt; &#39;required|string|max:255&#39;,<br>                &#39;password&#39;  =&gt; &#39;required|string&#39;<br>              ]);<br>if ($validator-&gt;fails()) {<br>    return response()-&gt;json($validator-&gt;errors());<br>}</pre><p>then add the code to authenticate the user.</p><pre>$credentials    =   $request-&gt;only(&#39;email&#39;, &#39;password&#39;);<br><br>if (! Auth::attempt($credentials)) {<br>    return response()-&gt;json([<br>        &#39;message&#39; =&gt; &#39;User not found&#39;<br>    ], 401);<br>}</pre><p>If successfully validated as a registered user then we will generate a token, but if it fails then we will give the response “user not found”<br>add the following code to generate token.</p><pre>$user   = User::where(&#39;email&#39;, $request-&gt;email)-&gt;firstOrFail();<br>$token  = $user-&gt;createToken(&#39;auth_token&#39;)-&gt;plainTextToken;<br><br>return response()-&gt;json([<br>    &#39;message&#39;       =&gt; &#39;Login success&#39;,<br>    &#39;access_token&#39;  =&gt; $token,<br>    &#39;token_type&#39;    =&gt; &#39;Bearer&#39;<br>]);</pre><p>Then register the controller that we have created in routes api.php with the post method.</p><pre>Route::post(&#39;/login&#39;, [AuthController::class, &#39;login&#39;]);</pre><p>Then run it on postman to test the login api</p><p>Method : POST</p><p>URL : <a href="http://127.0.0.1:8000/api/login">http://127.0.0.1:8000/api/login</a></p><p>Headers: Accept: application/json</p><p>Body : email, password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*_JD4y43egR5ZDxh9FJ_tZA.png" /><figcaption>post login user</figcaption></figure><p><strong>Get User</strong></p><p>To get user data we will directly call user data via routes api, so add the following code to routes/api.php</p><pre>  Route::middleware(&#39;auth:sanctum&#39;)-&gt;get(&#39;/user&#39;, function (Request $request) {<br>    return $request-&gt;user();<br>});</pre><p>Now try calling the user endpoint to get the logged in user information, don’t forget to add the bearer token to Auth Postman.</p><p>Method : GET</p><p>URL : <a href="http://127.0.0.1:8000/api/login">http://127.0.0.1:8000/api/login</a></p><p>Headers: Accept : application, json</p><p>Authorization: &lt;Bearer token&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*CIQ40WmCpU5ib9XEdQmGJA.png" /><figcaption>get user successful</figcaption></figure><p>It’s good that we have got the user we wanted, To ensure that the URL can only give a successful response if there is a token, try changing authorization with no auth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nPJaZajic89XGYM8TBB2RA.png" /><figcaption>get user failed</figcaption></figure><p>The api response will return the message: Unauthenticated. Good, this indicates that our URL is working as expected</p><p><strong>Logout</strong></p><p>It’s not good if we add login but not logout, so we add the following code to the logout function that we prepared previously.</p><pre>Auth::user()-&gt;tokens()-&gt;delete();<br>  return response()-&gt;json([<br>      &#39;message&#39; =&gt; &#39;Logout successfull’<br>  ]);</pre><p>Don’t forget to register the logout routes in the api.php file with the post method</p><pre>Route::middleware(&#39;auth:sanctum&#39;)-&gt;group(function () {<br>    Route::post(&#39;/logout&#39;, [AuthController::class, &#39;logout&#39;]);<br>});</pre><p>Now try to call the logout endpoint on our postman.</p><p>Method : POST</p><p>URL : <a href="http://127.0.0.1:8000/api/login">http://127.0.0.1:8000/api</a><a href="http://127.0.0.1:8000/api/login">/logout</a></p><p>Headers: Accept : application, json</p><p>Authorization: &lt;Bearer token&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KLMyYq-8jJA7SgW3NDto7Q.png" /></figure><p>Nice, now we have successfully implemented authentication using Laravel Sanctum. A simple method offered by Laravel.</p><p>Apart from using Laravel Sanctum, we can use the Laravel Passport authentication method or the JWT (JSON Web Token) method. We will discuss these two authentication methods another time. Have a good learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4eeaa99b472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter : Shared preferences, simple data storage key — value pair part 2]]></title>
            <link>https://medium.com/@hendriks96/flutter-shared-preferences-simple-data-storage-key-value-pair-part-2-b97cde03257e?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97cde03257e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 05:02:21 GMT</pubDate>
            <atom:updated>2023-08-24T05:02:21.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter : Shared preferences, simple data storage key — value pair part 2</h3><figure><img alt="imgae introduction" src="https://cdn-images-1.medium.com/max/1024/1*f25xZEVGNqcmuK7NP4xL7g.jpeg" /></figure><p>In the previous chapter, we managed to create a login session using a shared preference. If you forgot, you can see it <a href="https://medium.com/@hendriks96/flutter-shared-preferences-simple-data-storage-key-value-pair-c05eda0501e9"><strong>here</strong></a>. It’s incomplete if the user has logged in and can’t log out. In this tutorial we’ll get back into shared preferences. We will remove the shared preference when the user presses the logout button so that when the user opens the application again it will go to the login page. Let’s try.</p><p>Reopen the home_page.dart file in the previous project. On the AppBar we will add a logout button action. Add the following code inside the AppBar class.</p><pre>actions: [<br>  IconButton(<br>    icon: const Icon(Icons.logout),<br>    onPressed: () {},<br>   )<br>],</pre><p>So the AppBar code will be like this.</p><figure><img alt="AppBar code example" src="https://cdn-images-1.medium.com/max/940/1*XiUTVdJ7e-5gzDdCatFuCA.png" /><figcaption>AppBar code example</figcaption></figure><p>Now there is a logout button. It’s time we’ll insert a trigger when the button is pressed. Before the user log out it would be nice if we add a confirmation dialog before logging out.</p><p>Still in the same place, add the following code to bring up an alert dialog when the button is pressed in the onPressed method.</p><pre>showDialog(<br>  context: context,<br>  builder: (context) =&gt; AlertDialog(<br>    title: const Text(&#39;Confirmation&#39;),<br>    content: const Text(&#39;Are you sure to logout from application ?&#39;),<br>    actions: &lt;Widget&gt;[<br>      TextButton(<br>        child: const Text(&#39;Logout&#39;),<br>        onPressed: () {<br>          Navigator.of(context).pushAndRemoveUntil(<br>            MaterialPageRoute(<br>              builder: (context) =&gt; const LoginPage(),<br>            ),<br>            (Route&lt;dynamic&gt; route) =&gt; false,<br>          );<br>        },<br>      ),<br>      TextButton(<br>        child: const Text(&#39;Cancel&#39;),<br>        onPressed: () {<br>          Navigator.of(context).pop();<br>        },<br>      ),<br>    ],<br>  ),<br>);</pre><p>Run the application again, then if the button is pressed a confirmation dialog will appear before leaving the page.</p><figure><img alt="Show dialog confirmation" src="https://cdn-images-1.medium.com/max/600/1*OIP1XkO0G73Y_JVec0TS7A.gif" /><figcaption>Show dialog confirmation</figcaption></figure><p>Now the application is running according to what we want. After logging out try closing the application and reopening the application. What happened ?</p><p>The page that loads after the splash screen is the main page. This is not in accordance with the application flow in part 1.</p><p>Back to the home_page.dart page. On the logout button inside the dialog add the following code to remove the preferences from local storage.</p><pre>final SharedPreferences prefs = await SharedPreferences.getInstance();<br>await prefs.remove(&#39;islogin&#39;);</pre><p>Don’t forget to add async to the dialog’s onPressed method, so that the shared preference can run asynchronously.</p><figure><img alt="TextButton code example" src="https://cdn-images-1.medium.com/max/940/1*g-PF8qAEVtq6Feu-QO7nEA.png" /><figcaption>TextButton code example</figcaption></figure><p>Run the application again and see if the results are as we expected.</p><figure><img alt="Final result login app" src="https://cdn-images-1.medium.com/max/600/1*rlLtRLBqiOfA7oZYUihu-Q.gif" /><figcaption>Final result login app</figcaption></figure><p>Great, now the application is running according to the flowchart. To see the complete code, you can see it <a href="https://github.com/hendriks96/flutterxmedium/tree/shared_preference_example">here</a>.</p><p>To learn more about shared preferences you can look through their documentation.</p><p><strong>Reference</strong></p><ul><li><a href="https://pub.dev/packages/shared_preferences">shared_preferences | Flutter package</a></li><li><a href="https://developer.android.com/training/data-storage/shared-preferences">Save simple data with SharedPreferences | Android Developers</a></li><li><a href="https://developer.apple.com/documentation/foundation/nsuserdefaults">NSUserDefaults | Apple Developer Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97cde03257e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New Widget Button In Flutter]]></title>
            <link>https://medium.com/@hendriks96/new-widget-button-in-flutter-ad7b455dd894?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7b455dd894</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[button]]></category>
            <category><![CDATA[user-interface]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 10:59:59 GMT</pubDate>
            <atom:updated>2023-08-19T10:59:59.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7TH2F8op6QM23fG-WQZ9A.jpeg" /></figure><p>With Flutter we can make user interface components fast, attractive and easy to customize. Flutter provides several widgets that we can use right away. Since flutter version 2.O some components have started to be deprecated such as FlatButton, RaisedButton and OutlineButton. The button widget will be replaced with TextButton, ElevatedButton, and OutlinedButton. This is done because it is considered more flexible and easier to configure via constructors according to a quote from the flutter documentation “The overall goal is to make buttons more flexible, and easier to configure via constructor parameters or themes”. Likewise with the default theme, if you previously used ButtonTheme, then in the latest button it cannot be reused and instead flutter provides the TextButtonTheme, ElevatedButtonTheme, and OutlinedButtonTheme class to adjust the appearance of the user interface.</p><figure><img alt="New buton widget flutter" src="https://cdn-images-1.medium.com/max/940/1*GOH88zI6y-k19soDKOPhHw.png" /><figcaption>New buton widget flutter</figcaption></figure><p>As we can see in the picture above, it has been explained how the newest button widget class is where the FlatButton is replaced with a TextButton which can be used to create a button with a transparent background. RaisedButton was replaced with ElevatedButton which can be used to create buttons with colored backgrounds. OutlineButton is replaced with OutlinedButton. Quite easy to understand and remember instead of naming the previous widget.</p><p>We see a simple example below is the use of TextButton.</p><figure><img alt="TextButton Widget" src="https://cdn-images-1.medium.com/max/333/1*p7xt8G8ibq9vDL1woCqhwQ.png" /><figcaption>TextButton Widget</figcaption></figure><p>To make a button like in the picture, we can make it with code like the following.</p><pre>TextButton(<br>  onPressed: (){},<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p>As can be seen that the code is not much different from FlatButton. Next, how do we style the TextButton. We can simply call the ButtonStyle class inside the TextButton.</p><pre>TextButton(<br>  style: ButtonStyle(),<br>  onPressed: () {},<br>  child: const Text(&#39;Click Me&#39;),<br>)</pre><p>To create a style, for example changing the foreground color, we can use the foregroundColor parameter like this.</p><pre>foregroundColor : MaterialStateProperty.all&lt;Color&gt;(Colors.red),</pre><p>The code above will make the text red, as we know that the foreground will change the front or top of the stacked objects. On the TextButton the Text widget is in the foreground area. While the background area is transparent. To make the background color we can use the backgroundColor parameter inside the ButtonStyle class like this.</p><pre>backgroundColor: MaterialStateProperty.all&lt;Color&gt;(Colors.grey.shade300),</pre><figure><img alt="TextButton Widget with red text color" src="https://cdn-images-1.medium.com/max/333/1*QFy6sfo2FOSKPwC730QrGA.png" /><figcaption>Change text color in TextButton</figcaption></figure><p>As a suggestion it would be nice for us to use ElevatedButton to make the button look like above. Because by default ElevatedButton has provided a style for colored buttons.</p><p>Then what if we want to change the style of the text inside the button. Instead of using the TextStyle in the Text widget, we use the textStyle parameter in the ButtonStyle class.</p><pre>textStyle: MaterialStateProperty.all&lt;TextStyle&gt;(<br>  const TextStyle(<br>    letterSpacing: 2<br>  ),<br>),</pre><p>The code above will provide spacing between letters. Even though we can call the TextStyle class on the Text widget, it would be nice for us to take advantage of the parameters provided by the ButtonStyle class itself.</p><p><strong>ElevatedButton</strong></p><p>As explained above, we can use ElevatedButton to create colored buttons. By default ElevatedButton will be like this</p><figure><img alt="ElevatedButton Widget" src="https://cdn-images-1.medium.com/max/333/1*BdUbNo84NcRnISMeW6SIsA.png" /><figcaption>ElevatedButton Widget</figcaption></figure><p>To make the button above, we just need to make it like this</p><pre>ElevatedButton(<br>  onPressed: () {},<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p>The code has mandatory parameters like TextButton, but by default ElevatedButton has a colored style and has a shadow. To change the color we can take advantage of the same parameters as the TextButton class.</p><pre>ElevatedButton(<br>  onPressed: () {},<br>  style: ButtonStyle(<br>  backgroundColor:MaterialStateProperty.all&lt;Color&gt;(Colors.grey.shade300),<br>    foregroundColor: MaterialStateProperty.all&lt;Color&gt;(Colors.red),<br>  ),<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p><strong>OutlinedButton</strong></p><p>Next is the OutlinedButton widget which by default has a transparent background with a border on all edges.</p><figure><img alt="OutlinedButton Widget" src="https://cdn-images-1.medium.com/max/333/1*a4MUUyTzb1hUAlp6kxNT0w.png" /><figcaption>OutlinedButton Widget</figcaption></figure><p>Here is the code to create the button.</p><pre>OutlinedButton(<br>  onPressed: () {},<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p>Still the same and similar to ElevatedButton and TextButton. Likewise for changing the background and foreground colors of the OutlinedButton.</p><pre>OutlinedButton(<br>  onPressed: () {},<br>  style: ButtonStyle(<br>    backgroundColor: MaterialStateProperty.all&lt;Color&gt;(Colors.grey.shade300),<br>    foregroundColor: MaterialStateProperty.all&lt;Color&gt;(Colors.red),<br>  ),<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p>Still the same as the parameters in the ElevatedButton and TextButton. Apart from using the ButtonStyle to change the style of the TextButton, ElevatedButton and OutlinedButton we can also use the styleFrom() ButtonStyle utility methods.</p><pre>TextButton(<br>  onPressed: () {},<br>  style: TextButton.styleFrom(foregroundColor: Colors.red),<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><figure><img alt="OutlinedButton widget with red text color" src="https://cdn-images-1.medium.com/max/330/1*Ue8b2sLo8JzhUvIzIOOqwA.png" /><figcaption>OutlinedButton widget with red text color</figcaption></figure><p>How about ElevatedButton and OutlinedButton. Of course we can take advantage of the styleForm() in the widget.</p><pre>ElevatedButton(<br>  onPressed: () {},<br>  style: ElevatedButton.styleFrom(foregroundColor: Colors.red),<br>  child: const Text(&#39;Click Me&#39;),<br>),<br>OutlinedButton(<br>  onPressed: () {},<br>  style: OutlinedButton.styleFrom(foregroundColor: Colors.red),<br>  child: const Text(&#39;Click Me&#39;),<br>),</pre><p><strong>Conclusion</strong></p><p>Flutter makes it easy for us to develop mobile applications quickly, one of which is the button widget. In latest version of flutter we can use TextButton, ElevatedButton and OutlinedButton widgets to create button widgets. All of them have almost the same properties. We can make TextButton become ElevatedButton and OutlinedButton with the available properties as well as ElevatedButton and OutlinedButton. But it would be nice if we can use the widget according to the needs of our application so that the code remains clean and easy to understand. Use TextButton to make buttons that have a transparent background, use ElevatedButton to make buttons that have a background color, use OutlinedButton to make the background transparent and have a border around all edges.</p><p><strong>Reference</strong></p><p><a href="https://docs.flutter.dev/release/breaking-changes/buttons"><em>https://docs.flutter.dev/release/breaking-changes/buttons</em></a></p><p><a href="https://api.flutter.dev/flutter/material/ElevatedButton-class.html"><em>https://api.flutter.dev/flutter/material/ElevatedButton-class.html</em></a></p><p><a href="https://api.flutter.dev/flutter/material/TextButton-class.html"><em>https://api.flutter.dev/flutter/material/TextButton-class.html</em></a></p><p><a href="https://api.flutter.dev/flutter/material/OutlinedButton-class.html"><em>https://api.flutter.dev/flutter/material/OutlinedButton-class.html</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7b455dd894" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter : Shared preferences, simple data storage key — value pair]]></title>
            <link>https://medium.com/@hendriks96/flutter-shared-preferences-simple-data-storage-key-value-pair-c05eda0501e9?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05eda0501e9</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:25:31 GMT</pubDate>
            <atom:updated>2023-08-07T14:28:12.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter : Shared preferences, simple data storage key — value pair</h3><p>In this flutter topic, in the database session, we will introduce <a href="https://pub.dev/packages/shared_preferences">shared preferences</a>, a flutter plugin that is very easy to use when storing data into a database. Shared preference is a plugin that can be used to wrap platform-specific persistent storage for simple data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZdAm0kEsO5i-xiprUIHKfQ.jpeg" /></figure><p>The method used in shared preference is the key and value pair, where the key is a key that is used to get the value. One key can only have 1 value. Shared preferences are very suitable for storing temporary data, such as sessions or caches and are not recommended for storing important data. Shared preferences support several data types including int, double, bool, String, and List&lt;String&gt;.</p><p>To better understanding the use of shared preferences, we will create a simple application example like the login page. In this case we will use the shared preference as the user’s session to check whether the user has done it before or not. Where the use case example like this.</p><figure><img alt="Flowchart login page example" src="https://cdn-images-1.medium.com/max/250/1*VO9-12jMD8hGRdIm3bWxrw.jpeg" /><figcaption>flowchart example login page</figcaption></figure><p>As we can see in the flowchart above, after application opened by user it will be redirected to the splash page. This page will check whether the user has logged in before or not. If not, it will be directed to the login page, but if it is, the login page will be skipped and will be redirected to the home page. Can’t wait, let’s try it.</p><p>Next, create a flutter project first. then add the shared preference plugin to the flutter project. To add it you can type the following code in the terminal.</p><pre>flutter pub add shared_preferences</pre><p>or by adding it to the pubspec.yaml like this</p><figure><img alt="Add shared preference plugin in pubspec.yaml" src="https://cdn-images-1.medium.com/max/940/1*iI4U5hevU469_o1Twy8mkQ.png" /><figcaption>Dependency in pubspec.yaml</figcaption></figure><p>Then create 3 pages each having the name splash_page.dart (used for the application splashscreen page, the page that will be loaded when the application is opened), login_page.dart (used for the login page), home_page.dart (used for the main application page) .</p><figure><img alt="structure folder lib" src="https://cdn-images-1.medium.com/max/497/1*J2aIRyuXJ0RVj-hJQtaqNQ.png" /><figcaption>Structure folder lib</figcaption></figure><p>On the splash page page, we will create a simple display like this</p><figure><img alt="splashscreen page" src="https://cdn-images-1.medium.com/max/323/1*KjS28waU9oHtYV1qqSRmqA.png" /><figcaption>Splashscreen page</figcaption></figure><p>In the splash_page.dart file, create code like this to compile the layout.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:shared_preference_example/login_page.dart&#39;;<br><br>class SplashPage extends StatefulWidget {<br>  const SplashPage({super.key});<br><br>  @override<br>  State&lt;SplashPage&gt; createState() =&gt; _SplashPageState();<br>}<br><br>class _SplashPageState extends State&lt;SplashPage&gt; {<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Padding(<br>        padding: const EdgeInsets.all(16),<br>        child: Stack(<br>          children: [<br>            Align(<br>              child: FlutterLogo(<br>                size: MediaQuery.of(context).size.width / 3,<br>              ),<br>            ),<br>            const Align(<br>              alignment: Alignment.bottomCenter,<br>              child: CircularProgressIndicator(),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Open the main.dart file. Inside MaterialApp change the code from MyHomePage to SplashPage(). For the MyHomePage and _MyHomePageState classes, we will use them as the main page, so don’t delete them for the two classes.</p><figure><img alt="Class MyApp inside main.dart" src="https://cdn-images-1.medium.com/max/940/1*2lf4WcudWpEMrWDfa0KDkA.png" /><figcaption>Splashpage inside MyApp</figcaption></figure><p>Then run the program. Congratulations, the splash screen page has been completed. Next we will create a login page as shown below.</p><figure><img alt="Loginscreen page" src="https://cdn-images-1.medium.com/max/300/1*d9QaETmOLRb86Ox6abQalQ.jpeg" /><figcaption>Loginscreen page</figcaption></figure><p>Open the login_page.dart file. Then type the following code to display the login page.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:shared_preference_example/home_page.dart&#39;;<br><br>class LoginPage extends StatefulWidget {<br>  const LoginPage({super.key});<br><br>  @override<br>  State&lt;LoginPage&gt; createState() =&gt; _LoginPageState();<br>}<br><br>class _LoginPageState extends State&lt;LoginPage&gt; {<br>  final _formKey = GlobalKey&lt;FormState&gt;();<br><br>  TextEditingController txtUserName = TextEditingController();<br>  TextEditingController txtPassword = TextEditingController();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Login&#39;),<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(16),<br>        child: Center(<br>          child: Form(<br>            key: _formKey,<br>            child: Column(<br>              mainAxisSize: MainAxisSize.min,<br>              children: [<br>                const FlutterLogo(<br>                  size: 50,<br>                ),<br>                const SizedBox(<br>                  height: 50,<br>                ),<br>                TextFormField(<br>                  controller: txtUserName,<br>                  validator: (value) {<br>                    if (value == null || value.isEmpty) {<br>                      return &#39;username cannot be empty&#39;;<br>                    }<br>                    return null;<br>                  },<br>                  decoration: const InputDecoration(<br>                    labelText: &#39;Username&#39;,<br>                  ),<br>                ),<br>                const SizedBox(<br>                  height: 16,<br>                ),<br>                TextFormField(<br>                  controller: txtPassword,<br>                  validator: (value) {<br>                    if (value == null || value.isEmpty) {<br>                      return &#39;Password cannot be empty&#39;;<br>                    }<br>                    return null;<br>                  },<br>                  obscureText: true,<br>                  decoration: const InputDecoration(<br>                    labelText: &#39;Password&#39;,<br>                  ),<br>                ),<br>                const SizedBox(<br>                  height: 50,<br>                ),<br>                ElevatedButton(<br>                  onPressed: () {<br>                    if (_formKey.currentState!.validate()) {<br>                      ScaffoldMessenger.of(context).showSnackBar(<br>                          const SnackBar(content: Text(&#39;Processing Data&#39;)),<br>                      );<br>                    }<br>                  },<br>                  style: ElevatedButton.styleFrom(<br>                    minimumSize: const Size(double.infinity, 40),<br>                  ),<br>                  child: const Text(&#39;Login&#39;),<br>                )<br>              ],<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    txtUserName.dispose();<br>    txtPassword.dispose();<br>    super.dispose();<br>  }<br>}</pre><p>Return to the main.dart file and call the initstate method. This method is part of the flutter lifecycle. Add the following code to make the splashscreen page disappear within 5 seconds and be replaced with the login page.</p><pre>@override<br>void initState() {<br>  super.initState();<br>  Future.delayed(const Duration(seconds: 5)).then(<br>    (value) =&gt; Navigator.of(context).pushReplacement(<br>        MaterialPageRoute(builder: (context) =&gt; const LoginPage())),<br>  );<br>}</pre><p>Run the application and it will be like this.</p><figure><img alt="Splashscreen to login" src="https://cdn-images-1.medium.com/max/300/1*K3q3_KHmD3XoNjjgzxmFgg.gif" /><figcaption>Running application to login</figcaption></figure><p>The login page is finished, what about the main page, let’s continue.<br>Open the home_page.dart file. Do you still remember the MyHomePage and _MyHomePageState classes in the main.dart class.</p><p>Move the two classes in the home_page.dart file. don’t forget to import the material package. On this page we will write the title directly, so omit the title parameter in the MyHomePage constructor as well as the title declaration. Don’t forget to change the title on the app’s appbar. To keep the clean code., we can remove some of the comments then change the class names from MyHomePage to HomePage and _MyHomePageState to _HomePageState.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6luHdahL-_dLmS-PRr9sZg.png" /><figcaption>Final HomePage</figcaption></figure><p>Returning to the login page (login_page.dart) when the login button is pressed we will get a data processing message. We will change the button trigger so that when we press the button it will go to the main page. We will check if the username = ‘user’ and password = ‘user’ then it will be directed to the main page if it is wrong it will display a failed login message. Change the code in the onpressed function on the login button to be as follows.</p><pre>if (_formKey.currentState!.validate()) {<br>  if (txtUserName.text == &#39;user&#39; &amp;&amp;<br>      txtPassword.text == &#39;user&#39;) {<br>    Navigator.of(context).pushReplacement(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; const HomePage(),<br>      ),<br>    );<br>  } else {<br>    ScaffoldMessenger.of(context).showSnackBar(<br>      const SnackBar(content: Text(&#39;Login failed&#39;)),<br>    );<br>  }<br>}</pre><p>Run the application and see what happens.</p><figure><img alt="Insert username and password login" src="https://cdn-images-1.medium.com/max/300/1*nzVS2DwrlCJ5XEeq6CmI3w.gif" /><figcaption>Completing login form</figcaption></figure><p>Nice now the application is running almost perfectly. Try closing and reopening the application, after the splash screen, the application will return to the login page. This is not in accordance with the flowchart above. Let’s fix the application so that after the splash screen it will go to the main page using the shared preference.</p><p>Change the code when the login button is pressed. Initialize the shared preference first. Since initialization runs asynchronously, don’t forget to add async to the onPressed method.</p><pre>if (_formKey.currentState!.validate()) {<br>  if (txtUserName.text == &#39;user&#39; &amp;&amp;<br>      txtPassword.text == &#39;user&#39;) {<br>    final SharedPreferences prefs =<br>        await SharedPreferences.getInstance();<br>    await prefs.setBool(&#39;islogin&#39;, true);<br><br>    Navigator.of(context).pushReplacement(<br>      MaterialPageRoute(<br>        builder: (context) =&gt; const HomePage(),<br>      ),<br>    );<br>  } else {<br>    ScaffoldMessenger.of(context).showSnackBar(<br>      const SnackBar(content: Text(&#39;Login failed&#39;)),<br>    );<br>  }<br>}</pre><p>In the above code we will store boolean values ​​in preferences. The value will be stored in the islogin key</p><p>Reopen the splash_page.dart page, create a new method called onInit. Move all the code inside the initState method into onInit. Don’t forget to add code to fetch data from the shared preference that we saved earlier. While islogin is true then it will go to the home page but if it is false we will redirect to the login page. The complete code will be like this.</p><pre>void onInit() async {<br>    final SharedPreferences prefs = await SharedPreferences.getInstance();<br>    final isLogin = prefs.getBool(&#39;islogin&#39;) ?? false;<br><br>    if (isLogin) {<br>      Future.delayed(const Duration(seconds: 5)).then(<br>        (value) =&gt; Navigator.of(context).pushReplacement(<br>            MaterialPageRoute(builder: (context) =&gt; const HomePage())),<br>      );<br>    } else {<br>      Future.delayed(const Duration(seconds: 5)).then(<br>        (value) =&gt; Navigator.of(context).pushReplacement(<br>            MaterialPageRoute(builder: (context) =&gt; const LoginPage())),<br>      );<br>    }<br> }</pre><p>Don’t forget to call the onInit method on initState.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Q2UqcF9AEfuXIivSXsk1hw.png" /><figcaption>Moify initstate</figcaption></figure><p>In the above code we will check whether the user has logged in before or not by fetching data from the islogin preference. If not then it will go to the login page if it is then it will be redirected to the main page.</p><p>Run the application and voila the application is running as expected, isn’t it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*L_lVdWMzsEFcIrBCesaoEw.gif" /><figcaption>Final shared preference application</figcaption></figure><p>It’s not complete if we’ve logged in but there’s no logout button yet, let’s continue in the next part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c05eda0501e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove public from url laravel]]></title>
            <link>https://medium.com/@hendriks96/remove-public-from-url-laravel-13beb827be1f?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/13beb827be1f</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[framework]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 15:09:15 GMT</pubDate>
            <atom:updated>2023-08-02T15:09:15.020Z</atom:updated>
            <content:encoded><![CDATA[<p>If we run Laravel using Xampp, then when we access the website page, it will not automatically be redirected to the Laravel welcome page but will be directed first to the Laravel folder structure.</p><figure><img alt="Laravel Structure" src="https://cdn-images-1.medium.com/max/940/1*IGP7pA-hhHZL73eTgr_0PA.png" /><figcaption>laravel structure</figcaption></figure><p>Then when we want to see the website or we want to see the laravel main page, we can add “public” to the end of our url address.</p><figure><img alt="URL public laravel" src="https://cdn-images-1.medium.com/max/806/1*C5AiL-cDrERQTFv8XjOCrw.png" /><figcaption>URL public laravel</figcaption></figure><p>Then we can see the appearance of our home website.</p><figure><img alt="display laravel public" src="https://cdn-images-1.medium.com/max/940/1*2Cq3TBi0oyBjLH13sCz3CQ.png" /><figcaption>display laravel public</figcaption></figure><p>Of course this will make the URL address ugly and confuse the user, right? how to remove public in laravel url address. In this tutorial I will explain it, but before that if you don’t have a Laravel project you can make one first by reading my previous article about <a href="https://medium.com/@hendriks96/how-to-install-laravel-on-pc-60c39cc7f418?source=your_stories_page-------------------------------------">How To Install Laravel on PC</a>, next let’s remove the additional “public” on our Laravel page.</p><p>First enter into the laravel project that was previously created. Then go into the public folder, then we will find the .htaccess and index.php files here.</p><figure><img alt="konten public folder" src="https://cdn-images-1.medium.com/max/940/1*RhqySgxmSN8ygIwCysYkoA.png" /><figcaption>konten public folder</figcaption></figure><p>Then copy the file and paste it in the root of our laravel folder.</p><figure><img alt="location public folder" src="https://cdn-images-1.medium.com/max/940/1*zk1DktPa3YiOzLAq-DhFgA.png" /><figcaption>location public folder</figcaption></figure><p>For example here I paste from the first-project/public directory to the first-project directory.<br>Open the index.php file in the laravel root folder, then open it with a text editor and change some of the following code.</p><pre>__DIR__.&#39;/../storage/framework/maintenance.php&#39;</pre><p>To</p><pre>__DIR__.&#39;/storage/framework/maintenance.php&#39;</pre><pre>__DIR__.&#39;/../vendor/autoload.php&#39;</pre><p>To</p><pre>__DIR__.&#39;/vendor/autoload.php&#39;</pre><pre>__DIR__.&#39;/../bootstrap/app.php&#39;</pre><p>To</p><pre>__DIR__.&#39;/bootstrap/app.php&#39;</pre><p>Save the file then return to the browser and remove the extra “public” at the end of our url address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*KrsWs2Qra54DmA919MTI-w.png" /><figcaption>URL laravel without public</figcaption></figure><p>Then the laravel welcome page will appear</p><figure><img alt="welcome page laravel" src="https://cdn-images-1.medium.com/max/940/1*kufJXpkhpmhRiq5mF9BbBQ.png" /><figcaption>Welcome page</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13beb827be1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Install Laravel on PC]]></title>
            <link>https://medium.com/@hendriks96/how-to-install-laravel-on-pc-60c39cc7f418?source=rss-8d85c8a920d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/60c39cc7f418</guid>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Hendrik Setiawan]]></dc:creator>
            <pubDate>Sat, 24 Sep 2022 16:39:27 GMT</pubDate>
            <atom:updated>2022-09-24T16:39:27.971Z</atom:updated>
            <content:encoded><![CDATA[<p>laravel is a php based web framework that can be used to quickly build a websites without having write any configuration code from scratch. before starting to use laravel, we hope your computer has installed several applications that will be used, here we will install laravel on a windows computer.</p><p>first we need install this tools in windows computer:</p><ul><li>web server: you can use <a href="https://www.apachefriends.org/download.html">xampp</a>, <a href="https://www.wampserver.com/en/">wampp</a>, <a href="https://laragon.org/download/index.html">laragon </a>or etc…</li><li>dependency manager for php, you can use <a href="https://getcomposer.org/">composer</a></li></ul><p>when installing the web server, automatically we also install php on your computer, after everything is ready you can open a powershell on windows.<br>Type php -v to make sure that php is installed on your pc.</p><figure><img alt="checking php version" src="https://cdn-images-1.medium.com/max/940/1*e0tR9-r4iNXLSSIMztbUog.png" /><figcaption>checking php version on windows computer</figcaption></figure><p>To check the status of composer installed, you can use the command composer -v in powershell</p><figure><img alt="composer version" src="https://cdn-images-1.medium.com/max/909/1*-9e7hRuAKp8n_ozGNJQDkw.png" /><figcaption>check composer version</figcaption></figure><p>finished preparing, let’s start to install laravel.</p><p>Next we can go to the htdocs folder, this folder is inside the xampp folder, if you don’t change the web server installation location path, you can be found htdocs folder in <strong><em>C:\xampp\htdocs. </em></strong>Change the location of the path in powershell to <strong><em>C:\xampp\htdocs</em></strong>, type the following command in powershell.</p><pre>cd c:\xampp\htdocs</pre><figure><img alt="change to htdocs" src="https://cdn-images-1.medium.com/max/522/1*JWoCINdiMUwlLq1sIEb7bA.png" /><figcaption>change to htdocs directory</figcaption></figure><p>To start installing or create new project in laravel, you can type this command in powershell.</p><pre>composer create-project --prefer-dist laravel/laravel first-project</pre><p><em>Notes: first-project is the name of our project, we can change the name as needed.</em></p><p>Wait a few moments until the installation process is complete.</p><figure><img alt="progress installation" src="https://cdn-images-1.medium.com/max/940/1*cB2vTyNl6KpNvylqNIrAqg.png" /><figcaption>progress installation laravel</figcaption></figure><figure><img alt="installation success" src="https://cdn-images-1.medium.com/max/940/1*6UcAkS8FQK0etx25B2Onlg.png" /><figcaption>installation laravel success</figcaption></figure><p>It’s finished, then your laravel project will be in<strong><em> C:\xampp\htdocs\first-project.</em></strong></p><figure><img alt="directory laravel" src="https://cdn-images-1.medium.com/max/940/1*izmrOKPpkByfkzXawtZAxQ.png" /><figcaption>location laravel</figcaption></figure><p>Then run the xampp that was installed earlier.</p><figure><img alt="xampp dashboard" src="https://cdn-images-1.medium.com/max/940/1*UTj4OQq5_A34CM6UO6LAhA.png" /><figcaption>start apache in xampp</figcaption></figure><p>To see the results, we can run http://localhost/first-project/public/ in our browser.</p><p><em>Notes: first-project is the name of the project that has been created.</em></p><figure><img alt="laravel in xampp" src="https://cdn-images-1.medium.com/max/1024/1*04VvQSZ6Wp5sllABgV4wXA.png" /><figcaption>laravel display in xampp</figcaption></figure><p>Or without running xampp we can run the php artisan servecommand in powershell, but first move it to the first-project directory by typing thecd first-project command.</p><figure><img alt="start laravel artisan" src="https://cdn-images-1.medium.com/max/722/1*kkln8GVasArsHlWKrb1apA.png" /><figcaption>start php artisan</figcaption></figure><p>Then we can go tohttp://127.0.0.1:8000 or http://localhost:8000to see our website.</p><figure><img alt="laravel using artisan" src="https://cdn-images-1.medium.com/max/1024/1*_9BJQU3P4KSmpnm49KImCQ.png" /><figcaption>start laravel using artisan</figcaption></figure><p>And laravel has been installed, as we can see. When we run using xampp, then when accessing our website, we need to add “public” to the last part of our website address.</p><figure><img alt="address from xampp" src="https://cdn-images-1.medium.com/max/474/1*EQJMem7yZuaFBDp81H4B1A.png" /><figcaption>url using xampp</figcaption></figure><p>The next post will explain how to remove the additional public at the end of our website address. see you..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60c39cc7f418" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>