<?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 Zeba Rahman on Medium]]></title>
        <description><![CDATA[Stories by Zeba Rahman on Medium]]></description>
        <link>https://medium.com/@rahman.zeba?source=rss-8b5b553ede78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2Wz_h_BN6879KTW-8emVFw.jpeg</url>
            <title>Stories by Zeba Rahman on Medium</title>
            <link>https://medium.com/@rahman.zeba?source=rss-8b5b553ede78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:30:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahman.zeba/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[Laravel 7 — Showing localised prices with currency conversion]]></title>
            <link>https://medium.com/fabcoding/laravel-7-showing-localised-prices-with-currency-conversion-b8bee703ded2?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8bee703ded2</guid>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 03:21:19 GMT</pubDate>
            <atom:updated>2020-10-02T03:21:19.711Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel 7 — Showing localised prices with currency conversion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_9gscD0suZAdyCmBS5kV4Q.png" /></figure><p>If you’re creating an application that supports international purchases, you would definitely want to show the prices in the user’s localised currency and formatting (since different countries have different formats). Doing this cleanly and efficiently would be a challenge. So we will be using 2 packages by Daniel Stainback that will make this easy and efficient.</p><h3>Part A — Installation and Configuration</h3><p><strong>Install the packages</strong></p><p>We will install 2 packages. The torann/currency package for currency conversion and formatting, and the torann/geoip package for detecting the local currency of the user.</p><pre>composer require torann/currency<br>composer require torann/geoip</pre><p>Let us publish the config and migration files so that we can make changes.</p><pre>php artisan vendor:publish --provider=&quot;Torann\Currency\CurrencyServiceProvider&quot; --tag=config<br>php artisan vendor:publish --provider=&quot;Torann\Currency\CurrencyServiceProvider&quot; --tag=migrations<br>php artisan vendor:publish --provider=&quot;Torann\GeoIP\GeoIPServiceProvider&quot; --tag=config</pre><p>Then run the migrate command to build the tables.</p><pre>php artisan migrate</pre><p><strong>Configure Currency</strong></p><p>Add the supported currencies to our project database</p><pre>php artisan currency:manage add usd,gbp,cad,aud,sek,inr,cny,eur</pre><p><strong>Data for exhcange rates</strong></p><p>We will use <a href="https://openexchangerates.org/signup/free">OpenExchangeRates.org</a> for getting the exchange rate data. Create a free account, Get the API key (App ID) and add it to our project environment variables.</p><p><strong><em>.env</em></strong></p><pre>OPEN_EXCHANGE_RATE_KEY=<strong>&lt;API KEY&gt;</strong></pre><p>and then replace key attribute in the config file</p><p><strong><em>config/currency.php</em></strong></p><pre>&#39;api_key&#39; =&gt; env(&#39;OPEN_EXCHANGE_RATE_KEY&#39;),</pre><p><strong>Update the exchange rates</strong></p><p>For updating the exchange rate to the latest data, run the command</p><pre>php artisan currency:update -o</pre><blockquote><strong><em>Imprtant Note:</em></strong><em> You will need to run this command on regular intervals, for example, once every day so that the rates in your database are up to date.</em></blockquote><blockquote><em>For this you can use a cron job.</em></blockquote><p><strong>Set default currency</strong></p><p>Set the default currency in the following file, which will be used when no currency is chosen.</p><p><strong><em>config/currency.php</em></strong></p><pre>&#39;default&#39; =&gt; &#39;USD&#39;,</pre><p><strong>Alternatively</strong>, you can set default currency in environment variables and just reference it here, this way it can be modified easily, later on.</p><p><strong><em>.env</em></strong></p><pre>DEFAULT_CURRENCY=<strong>USD</strong></pre><p><strong><em>config/currency.php</em></strong></p><pre>&#39;default&#39; =&gt; env(&#39;DEFAULT_CURRENCY&#39;, &#39;USD&#39;),</pre><p><strong>Configure GeoIP</strong></p><p>The library uses cache tags but this is not supported on Laravel installations that use the file or database cache driver, so let us remove it.</p><p><strong><em>config/geoip.php file</em></strong></p><pre>&#39;cache_tags&#39; =&gt; <strong>false</strong>,</pre><p>for locating IPs we will use <a href="https://ip-api.com/">IP-API</a>. They allow up to 150 requests per minute, for free, without an API key.</p><p><strong>Later</strong> if you want to handle more requests, you will subscribe to their plan and add the API key:</p><p><strong><em>.env</em></strong></p><pre>IPAPI_KEY=<strong>&lt;KEY&gt;</strong></pre><h3>Part B — Setting a default currency for the current user’s current session</h3><p>The library provides a middleware <strong>CurrencyMiddleware</strong> that will allow setting the local currency of the current user for the session.</p><p>So let’s add this middleware to our project</p><p><strong><em>app/Http/Kernel.php</em></strong></p><p>Include the <strong>CurrencyMiddleware </strong>class AFTER the <strong>StartSession</strong> class within the <strong><em>web </em></strong>array of <strong><em>$middlewareGroups</em></strong> :</p><pre>protected $middlewareGroups = [<br>    &#39;<strong>web</strong>&#39; =&gt; [<br>        ...<br>        \Illuminate\Session\Middleware\StartSession::<em>class</em>,<br><strong>        \Torann\Currency\Middleware\CurrencyMiddleware::class,<br></strong>        ...<br>    ],<br>];</pre><p>Using <em>GeoIP</em>, we will detect the local currency of the current location of the user, and attach this to the user’s current session. The user’s session may change so its ideal to put this logic in a middleware. So let us create a new middleware</p><pre>php artisan make:middleware UserCurrencyMiddleware</pre><p>Go to the file that was just created and add the function</p><p><strong><em>app/Http/Middleware/UserCurrencyMiddleware.php</em></strong></p><pre><strong>public function </strong>handle(Request $request, Closure $next) {<br><strong>  if </strong>(! $request-&gt;get(&#39;currency&#39;) &amp;&amp; ! $request-&gt;getSession()-&gt;get(&#39;currency&#39;)) {<br>    $clientIP = $request-&gt;getClientIp();<br>    $localCurrency = geoip($clientIP)-&gt;getAttribute(&#39;currency&#39;);</pre><pre>    $request-&gt;getSession()-&gt;put([<br>      &#39;currency&#39; =&gt; $localCurrency,<br>    ]);<br>  }</pre><pre><strong>  return </strong>$next($request);<br>}</pre><p>As you have can see from the code, apart from automatic detection, <strong>this also enables you to send ‘currency’ attribute in any request to set the user’s default currency to a custom value.</strong></p><p>We need this to run after <strong>StartSession</strong> and just before the <strong>CurrencyMiddleware. </strong>So again, modify the kernel file.</p><p><strong><em>app/Kernel.php</em></strong></p><p>Include the <strong>CurrencyMiddleware </strong>class AFTER the <strong>StartSession</strong> class within the <strong><em>web </em></strong>array of <strong><em>$middlewareGroups</em></strong> :</p><pre>protected $middlewareGroups = [<br>    &#39;<strong>web</strong>&#39; =&gt; [<br>        ...<br>        \Illuminate\Session\Middleware\StartSession::<em>class</em>,<br><strong>        \App\Http\Middleware\UserCurrencyMiddleware::class,<br>        \Torann\Currency\Middleware\CurrencyMiddleware::class,<br></strong>        ...<br>    ],<br>];</pre><p>That’s it! Now you can use the methods anywhere in your code.</p><p>To get user’s currency:</p><pre>$currency = currency()-&gt;getUserCurrency();</pre><p>To format a price, stored in a given currency (say, USD), converted to user’s currency and also formatted to it.</p><pre>$str = currency(5.99, &#39;USD&#39;, currency()-&gt;getUserCurrency());</pre><p>…</p><p>I hope this was helpful. If you have any questions, feel free to comment.</p><p>…</p><p><em>Also published at </em><a href="http://new.fabcoding.com/2020/10/02/laravel-7-showing-localised-prices-with-currency-conversion/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bee703ded2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/laravel-7-showing-localised-prices-with-currency-conversion-b8bee703ded2">Laravel 7 — Showing localised prices with currency conversion</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel 7 — Create a subscription system using Cashier & Stripe]]></title>
            <link>https://medium.com/fabcoding/laravel-7-create-a-subscription-system-using-cashier-stripe-77cdf5c8ea5d?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/77cdf5c8ea5d</guid>
            <category><![CDATA[subscription]]></category>
            <category><![CDATA[cashier]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 00:24:22 GMT</pubDate>
            <atom:updated>2020-10-01T00:25:56.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel 7 — Create a subscription system using Cashier &amp; Stripe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4sZ924xQs1wWlCpoTIDIlA.jpeg" /></figure><p>The latest versions of Laravel and Cashier have brought many changes and made it significantly easier to build features in our web applications. In this tutorial, we will build a simple subscription system using Stripe.</p><h3>1. Install the Cashier package</h3><p>Run the following command.</p><pre>composer require laravel/cashier</pre><p>This will install migrations for adding required columns to the users table, and also create a subscriptions table. So let us run the migrations.</p><pre>php artisan migrate</pre><p>Optionally, you can publish the migration files to your project database directory along with other migrations.</p><pre>php artisan vendor:publish --tag=&quot;cashier-migrations&quot;</pre><p>We will also require stripe-php package later for retrieving our subsriptions from our stripe account, so let us install it also.</p><pre>composer require stripe/stripe-php</pre><h3>2. Modify the User model</h3><p><strong><em>User.php</em></strong></p><p>Add the <em>Billable</em> trait to the <em>User</em> model.</p><pre>&lt;?php<br>namespace App;</pre><pre>...<br><strong>use Laravel\Cashier\Billable;</strong></pre><pre>class User extends Authenticatable {<br><strong>  use Billable;</strong><br>  ...<br>}</pre><h3>3. Configure Stripe</h3><p>Go to <a href="http://stripe.com/">Stripe.com</a>. Create an account and go to your <em>Dashboard</em>. There are 2 steps to be followed here</p><h3>3.1. Create subscription plans</h3><p><strong>First</strong>, Here we need to create a <strong><em>Product</em></strong> for each of the <em>subscription plans</em> we want to offer. Set a name and a price for each.</p><p><strong><em>Dashboard -&gt; Products</em></strong></p><p>For this example, I have created 2 plans, <em>Basic</em> and <em>Premium</em>, priced at<em> £ 10.00</em> and<em> £ 50.00</em> respectively.</p><h3>3.2. Set the API keys</h3><p>Grab the API keys from Stripe.</p><p><strong><em>Dashboard -&gt; Developers -&gt; API Keys</em></strong></p><p>Copy the <em>Publishable Key</em> and the <em>Secret Key</em> and add them in the <em>.env</em> file. Also, add the currency in the file, same as the one you selected in the Stripe dashboard.</p><p><strong><em>project/.env file</em></strong></p><pre>STRIPE_KEY=your publishable key here<br>STRIPE_SECRET=your secret here</pre><pre>CASHIER_CURRENCY=gbp</pre><p>Also in the services file,</p><p><strong><em>config/sevices.php</em></strong></p><p>Add the following array</p><pre>&#39;stripe&#39; =&gt; [<br>  &#39;model&#39; =&gt; App\User::class,<br>  &#39;key&#39; =&gt; env(&#39;STRIPE_KEY&#39;),<br>  &#39;secret&#39; =&gt; env(&#39;STRIPE_SECRET&#39;),<br>],</pre><p>Now we can start working on the main feature.</p><h3>4. The controller</h3><p>Run the command to create a new controller</p><pre>php artisan make:controller SubscriptionController</pre><p>Go to the created file</p><p><strong><em>app/Http/Controllers/SubscriptionController.php</em></strong></p><p>Add the necessary imports on the top.</p><pre>&lt;?php</pre><pre>namespace App\Http\Controllers;</pre><pre><strong>require_once(&#39;../vendor/autoload.php&#39;);</strong></pre><pre>use App\Http\Controllers\Controller;<br>use Illuminate\Http\Request;<br><strong>use Illuminate\Support\Facades\Auth;</strong><br><strong>use Laravel\Cashier\Cashier;</strong><br><strong>use \Stripe\Stripe;</strong></pre><pre>class SubscriptionController extends Controller {</pre><pre>}</pre><p>Now write the functions inside the class.</p><pre>public function __construct() {<br>       $this-&gt;middleware(&#39;auth&#39;);<br>   }</pre><pre>   public function retrievePlans() {<br>       $key = \config(&#39;services.stripe.secret&#39;);<br>       $stripe = new \Stripe\StripeClient($key);<br>       $plansraw = $stripe-&gt;plans-&gt;all();<br>       $plans = $plansraw-&gt;data;<br>       <br>       foreach($plans as $plan) {<br>           $prod = $stripe-&gt;products-&gt;retrieve(<br>               $plan-&gt;product,[]<br>           );<br>           $plan-&gt;product = $prod;<br>       }<br>       return $plans;<br>   }</pre><pre>   public function showSubscription() {</pre><pre>       $plans = $this-&gt;retrievePlans();<br>       $user = Auth::user();<br>       <br>       return view(&#39;seller.pages.subscribe&#39;, [<br>           &#39;user&#39;=&gt;$user,<br>           &#39;intent&#39; =&gt; $user-&gt;createSetupIntent(),<br>           &#39;plans&#39; =&gt; $plans<br>       ]);<br>   }</pre><pre>   public function processSubscription(Request $request)<br>   {<br>       $user = Auth::user();<br>       $paymentMethod = $request-&gt;input(&#39;payment_method&#39;);<br>                   <br>       $user-&gt;createOrGetStripeCustomer();<br>       $user-&gt;addPaymentMethod($paymentMethod);<br>       $plan = $request-&gt;input(&#39;plan&#39;);</pre><pre>       try {<br>           $user-&gt;newSubscription(&#39;default&#39;, $plan)-&gt;create($paymentMethod, [<br>               &#39;email&#39; =&gt; $user-&gt;email<br>           ]);<br>       } catch (\Exception $e) {<br>           return back()-&gt;withErrors([&#39;message&#39; =&gt; &#39;Error creating subscription. &#39; . $e-&gt;getMessage()]);<br>       }<br>       <br>       return redirect(&#39;dashboard&#39;);<br>   }</pre><p>Now we have the controller for returning the list of stripe plans to our subscription view.</p><h3>6. The routes</h3><p><strong>routes/web.php</strong></p><pre><strong>Route::get(&#39;/subscribe&#39;, &#39;SubscriptionController@showSubscription&#39;);</strong><br><strong>      Route::post(&#39;/subscribe&#39;, &#39;SubscriptionController@processSubscription&#39;);</strong></pre><pre>      // welcome page only for subscribed users<br><strong>      Route::get(&#39;/welcome&#39;, &#39;SubscriptionController@showWelcome&#39;)-&gt;middleware(&#39;subscribed&#39;);</strong></pre><p>The first 2 routes are the ones we are working with. The next, welcome route, has a middleware, we will be discussing that in the last step of this tutorial, so don’t pay attention to it now.</p><h3>7. The views</h3><p><strong><em>resources/views/subscribe.blade.php</em></strong></p><p>Here, I will show only the relevant parts of the view, because your theme, scaffolding, and view would be entirely different.</p><p>Add the styles required for the Stripe element (shown for entering card details), at the top.</p><pre>&lt;style&gt;<br>    .StripeElement {<br>        background-color: white;<br>        padding: 8px 12px;<br>        border-radius: 4px;<br>        border: 1px solid transparent;<br>        box-shadow: 0 1px 3px 0 #e6ebf1;<br>        -webkit-transition: box-shadow 150ms ease;<br>        transition: box-shadow 150ms ease;<br>    }<br>    .StripeElement--focus {<br>        box-shadow: 0 1px 3px 0 #cfd7df;<br>    }<br>    .StripeElement--invalid {<br>        border-color: #fa755a;<br>    }<br>    .StripeElement--webkit-autofill {<br>        background-color: #fefde5 !important;<br>    }<br>&lt;/style&gt;</pre><p>Now create the form. Here I am showing a view with a list of plans as radio selection option. You can choose a better way to display and choose it. Just make sure the value is submitted correctly in the form submission.</p><pre>&lt;form action=&quot;/seller/subscribe&quot; method=&quot;POST&quot; id=&quot;subscribe-form&quot;&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            @foreach($plans as $plan)</pre><pre>            &lt;div class=&quot;col-md-4&quot;&gt;</pre><pre>                &lt;div class=&quot;subscription-option&quot;&gt;<br>                    &lt;input type=&quot;radio&quot; id=&quot;plan-silver&quot; name=&quot;plan&quot; value=&#39;{{$plan-&gt;id}}&#39;&gt;<br>                    &lt;label for=&quot;plan-silver&quot;&gt;<br>                        &lt;span class=&quot;plan-price&quot;&gt;{{$plan-&gt;currency}}{{$plan-&gt;amount/100}}&lt;small&gt; /{{$plan-&gt;interval}}&lt;/small&gt;&lt;/span&gt;<br>                        &lt;span class=&quot;plan-name&quot;&gt;{{$plan-&gt;product-&gt;name}}&lt;/span&gt;<br>                    &lt;/label&gt;<br>                &lt;/div&gt;</pre><pre>            &lt;/div&gt;</pre><pre>            @endforeach</pre><pre>        &lt;/div&gt;<br>    &lt;/div&gt;</pre><pre>    &lt;input id=&quot;card-holder-name&quot; type=&quot;text&quot;&gt;&lt;label for=&quot;card-holder-name&quot;&gt;Card Holder Name&lt;/label&gt;</pre><pre>    @csrf<br>    &lt;div class=&quot;form-row&quot;&gt;<br>        &lt;label for=&quot;card-element&quot;&gt;Credit or debit card&lt;/label&gt;<br>        &lt;div id=&quot;card-element&quot; class=&quot;form-control&quot;&gt;</pre><pre>        &lt;/div&gt;</pre><pre>        &lt;!-- Used to display form errors. --&gt;<br>        &lt;div id=&quot;card-errors&quot; role=&quot;alert&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;stripe-errors&quot;&gt;&lt;/div&gt;</pre><pre>    @if (count($errors) &gt; 0)<br>    &lt;div class=&quot;alert alert-danger&quot;&gt;<br>        @foreach ($errors-&gt;all() as $error)<br>        {{ $error }}&lt;br&gt;<br>        @endforeach<br>    &lt;/div&gt;<br>    @endif</pre><pre>    &lt;div class=&quot;form-group text-center&quot;&gt;<br>        &lt;button  id=&quot;card-button&quot; data-secret=&quot;{{ $intent-&gt;client_secret }}&quot; class=&quot;btn btn-lg btn-success btn-block&quot;&gt;SUBMIT&lt;/button&gt;<br>    &lt;/div&gt;</pre><pre>&lt;/form&gt;</pre><p>Immediately below the closing tag of the FORM element, add the following javascript.</p><pre>&lt;script src=&quot;https://js.stripe.com/v3/&quot;&gt;&lt;/script&gt;</pre><pre>&lt;script&gt;</pre><pre>    var stripe = Stripe(&#39;{{ env(&#39;STRIPE_KEY&#39;) }}&#39;);<br>    var elements = stripe.elements();<br>    var style = {<br>        base: {<br>            color: &#39;#32325d&#39;,<br>            fontFamily: &#39;&quot;Helvetica Neue&quot;, Helvetica, sans-serif&#39;,<br>            fontSmoothing: &#39;antialiased&#39;,<br>            fontSize: &#39;16px&#39;,<br>            &#39;::placeholder&#39;: {<br>                color: &#39;#aab7c4&#39;<br>            }<br>        },<br>        invalid: {<br>            color: &#39;#fa755a&#39;,<br>            iconColor: &#39;#fa755a&#39;<br>        }<br>    };</pre><pre>    var card = elements.create(&#39;card&#39;, {hidePostalCode: true,<br>        style: style});</pre><pre>    card.mount(&#39;#card-element&#39;);</pre><pre>    card.addEventListener(&#39;change&#39;, function(event) {<br>        var displayError = document.getElementById(&#39;card-errors&#39;);<br>        if (event.error) {<br>            displayError.textContent = event.error.message;<br>        } else {<br>            displayError.textContent = &#39;&#39;;<br>        }<br>    });</pre><pre>    const cardHolderName = document.getElementById(&#39;card-holder-name&#39;);<br>    const cardButton = document.getElementById(&#39;card-button&#39;);<br>    const clientSecret = cardButton.dataset.secret;</pre><pre>    cardButton.addEventListener(&#39;click&#39;, async (e) =&gt; {<br>        console.log(&quot;attempting&quot;);<br>        const { setupIntent, error } = await stripe.confirmCardSetup(<br>            clientSecret, {<br>                payment_method: {<br>                    card: card,<br>                    billing_details: { name: cardHolderName.value }<br>                }<br>            }<br>            );</pre><pre>        if (error) {<br>            var errorElement = document.getElementById(&#39;card-errors&#39;);<br>            errorElement.textContent = error.message;</pre><pre>        } else {</pre><pre>            paymentMethodHandler(setupIntent.payment_method);<br>        }<br>    });</pre><pre>    function paymentMethodHandler(payment_method) {<br>        var form = document.getElementById(&#39;subscribe-form&#39;);<br>        var hiddenInput = document.createElement(&#39;input&#39;);<br>        hiddenInput.setAttribute(&#39;type&#39;, &#39;hidden&#39;);<br>        hiddenInput.setAttribute(&#39;name&#39;, &#39;payment_method&#39;);<br>        hiddenInput.setAttribute(&#39;value&#39;, payment_method);<br>        form.appendChild(hiddenInput);</pre><pre>        form.submit();<br>    }</pre><pre>&lt;/script&gt;</pre><p>Awesome! Now you can navigate to the <strong><em>/seller/subscribe</em></strong> route and use test credentials of Stripe payment and test it out! It should work if you didn’t mess up.</p><h3>Checking the subscription status</h3><p>Now you might want to redirect the user to subscribe page directly if they are not already subscribed and to a dashboard of they are already subscribed. Or you may want to show a button and information in the profile/dashboard according to subscription status. You can use the following snippets for checking.</p><p>Pay attention to the name of subscription ‘default’ when performing such actions. All the methods return true/false.</p><pre>Auth::user()-&gt;subscribed(&#39;default&#39;);  //Check if user is subscribed<br>Auth::user()-&gt;subscription(&#39;main&#39;)-&gt;onGracePeriod(); //cancelled but current subscription has not ende<br>Auth::user()-&gt;onPlan(&#39;bronze&#39;); //check which plan.<br>Auth::user()-&gt;subscription(&#39;default&#39;)-&gt;cancelled(); //user earlier had a sibscription but cancelled (and no longer on grace period)</pre><h3>Protecting routes</h3><p>We defined a <strong>route</strong> above for a ‘<em>welcome</em>’ page only for subscribed users, with a middleware named <strong><em>Subscribed</em></strong>. Let us work on that now.</p><p>Some pages you may want to display only if the user is subscribed, otherwise, it should not display at all; the route should not work for the non-subscribed users. We can achieve this using a <em>middleware, </em>in <strong>4 simple steps.</strong></p><p><strong>First</strong>, create the middleware.</p><pre>php artisan make:middleware Subscribed</pre><p><strong>Second</strong>, to the newly created file and replace the code.</p><p><strong><em>app/Http/Middleware/Subscribed.php</em></strong></p><pre>&lt;?php<br>namespace App\Http\Middleware;<br>use Closure;</pre><pre>class Subscribed {</pre><pre>  public function handle($request, Closure $next) {<br>    if ($request-&gt;user() and ! $request-&gt;user()-&gt;subscribed(&#39;default&#39;))<br>      return redirect(&#39;subscribe&#39;);</pre><pre>    return $next($request);<br>  }<br>}</pre><p><strong>Third</strong>, go the Kernel file and add the middleware.</p><p><strong><em>app/Http/Kernel.php</em></strong></p><p>Add the middleware to the <em>routeMiddleware</em> array.</p><pre>protected $routeMiddleware = [<br>...<br><strong>&#39;subscribed&#39; =&gt; \App\Http\Middleware\Subscribed::class,</strong><br>];</pre><p><strong>Fourth</strong>, just add the middleware to the routes you want to protect</p><p><strong><em>routes/web.php</em></strong></p><pre>Route::get(&#39;/welcome&#39;, &#39;Seller\SubscriptionController@showWelcome&#39;)-&gt;middleware(&#39;subscribed&#39;);</pre><p>Or, if you wish to use this for several routes, wrap them in a group like this:</p><pre>Route::group([&#39;middleware&#39; =&gt; [&#39;role:seller&#39;]], function () {<br>  Route::get(&#39;/welcome&#39;, &#39;Seller\SubscriptionController@showWelcome&#39;);<br>  ...<br>});</pre><p>If this helped you, share, clap, and leave a comment!</p><p>…</p><p><em>Originally published on </em><a href="http://new.fabcoding.com/2020/10/01/laravel-7-create-a-subscription-system-using-cashier-stripe/"><em>Fabcoding</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77cdf5c8ea5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/laravel-7-create-a-subscription-system-using-cashier-stripe-77cdf5c8ea5d">Laravel 7 — Create a subscription system using Cashier &amp; Stripe</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel REST API — 2. CRUD Operations]]></title>
            <link>https://medium.com/fabcoding/laravel-rest-api-2-crud-operations-2ca4ef743440?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ca4ef743440</guid>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 19:07:08 GMT</pubDate>
            <atom:updated>2020-08-15T19:08:04.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5DctiOS7LNbLvYxO.png" /></figure><p>Assuming you have an existing Laravel project, we will create a database for Books and we will write endpoints for its CRUD operations, which means Create, Read, Update and Delete. We will create the following endpoints:</p><p><strong>GET /api/books</strong> : to return a list of all the books</p><p><strong>GET /api/books/{id}</strong> : to return details of a particular book by ID</p><p><strong>POST /api/books</strong> : to create a new book</p><p><strong>PUT /api/books/{id}</strong> : to update details of a book by iD</p><p><strong>DELETE /api/books/{id}</strong> : to delete a book by ID</p><p>So let’s get started.</p><p><em>Note: If you don’t have an existing Laravel project, please check </em><a href="https://fabcoding.com/set-up-laravel-homestead-on-mac-step-by-step/"><em>this</em></a><em> and </em><a href="https://fabcoding.com/laravel-rest-api-1-authentication/"><em>this</em></a><em>.</em></p><h4>Step 1</h4><p><strong>Create the model</strong></p><p>First we create the model of the book.</p><pre>php artisan make:model Book -m</pre><p>This will generate 2 things — the model php file and the migration for the database table. Let us edit both the files to have all the fields we require.</p><p><strong><em>app/Book.php</em></strong></p><pre>&lt;?php<br>namespace App;<br>use Illuminate\Database\Eloquent\Model;<br>class Book extends Model {<br>  <strong>protected $fillable = [</strong><br><strong>    &#39;name&#39;, &#39;author&#39;</strong><br><strong>  ];</strong><br>}</pre><p><strong><em>database/migrations/xxx.xxx_create_books_table.php</em></strong></p><p>Modify the up() function here</p><pre>...<br>public function up()<br>{<br>    Schema::create(&#39;books&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;string(&#39;name&#39;);<br>        $table-&gt;string(&#39;author&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}<br>...</pre><p>Now run the command</p><pre>php artisan migrate</pre><p>Our model and database are ready now.</p><h4>Step 2</h4><p><strong>The controller</strong></p><p>Now we will create a controller which will hold all the methods for the API. Run the following command to create a controller.</p><pre>php artisan make:controller Api/BookController</pre><p>Open the newly created file.</p><p><strong><em>app/Http/Controllers/Api/BookController.php</em></strong></p><pre>&lt;?php<br><br>namespace App\Http\Controllers;<br><br>use Illuminate\Http\Request;<br>use App\Book;<br><br>class BookController extends Controller {<br>    <br>}</pre><p>Now write functions logic for each of the endpoints.</p><p><em>1. Function to get all the books from the database table.</em></p><pre>public function getAllBooks() {<br>      $books = Book::get()-&gt;toJson(JSON_PRETTY_PRINT);<br>      return response($books, 200);<br>    }</pre><p><em>2. Function to get a particular book by ID</em></p><pre>public function getBook($id) {<br>      if (Book::where(&#39;id&#39;, $id)-&gt;exists()) {<br>        $book = Book::where(&#39;id&#39;, $id)-&gt;get()-&gt;toJson(JSON_PRETTY_PRINT);<br>        return response($book, 200);<br>      } else {<br>        return response()-&gt;json([<br>          &quot;message&quot; =&gt; &quot;Book not found&quot;<br>        ], 404);<br>      }<br>    }</pre><p><em>3. Function to create a new book</em></p><pre>public function createBook(Request $request) {<br>      $book = new Book;<br>      $book-&gt;name = $request-&gt;name;<br>      $book-&gt;author = $request-&gt;author;<br>      $book-&gt;save();<br><br>      return response()-&gt;json([<br>        &quot;message&quot; =&gt; &quot;Book record created&quot;<br>      ], 201);<br>    }</pre><p><em>4. Function to update a book by ID</em></p><pre>public function updateBook(Request $request, $id) {<br>      if (Book::where(&#39;id&#39;, $id)-&gt;exists()) {<br>        $book = Book::find($id);<br><br>        $book-&gt;name = is_null($request-&gt;name) ? $book-&gt;name : $book-&gt;name;<br>        $book-&gt;author = is_null($request-&gt;author) ? $book-&gt;author : $book-&gt;author;<br>        $book-&gt;save();<br><br>        return response()-&gt;json([<br>          &quot;message&quot; =&gt; &quot;records updated successfully&quot;<br>        ], 200);<br>      } else {<br>        return response()-&gt;json([<br>          &quot;message&quot; =&gt; &quot;Book not found&quot;<br>        ], 404);<br>      }<br>    }</pre><p><em>5. Function to delete a book by ID</em></p><pre>public function deleteBook ($id) {<br>      if(Book::where(&#39;id&#39;, $id)-&gt;exists()) {<br>        $book = Book::find($id);<br>        $book-&gt;delete();<br><br>        return response()-&gt;json([<br>          &quot;message&quot; =&gt; &quot;records deleted&quot;<br>        ], 202);<br>      } else {<br>        return response()-&gt;json([<br>          &quot;message&quot; =&gt; &quot;Book not found&quot;<br>        ], 404);<br>      }<br>    }</pre><p>Now that we have written all the logic, let us define routes for these.</p><h4>Step 3</h4><p><strong>The routes</strong></p><p>Add the routes to the API routes file, to access all the functions we wrote.</p><p><strong><em>routes/api.php</em></strong></p><pre>Route::get(&#39;books&#39;, &#39;Api\BookController@getAllBooks&#39;);<br>Route::get(&#39;books/{id}&#39;, &#39;Api\BookController@getBook&#39;);<br>Route::post(&#39;books&#39;, &#39;Api\BookController@createBook&#39;);<br>Route::put(&#39;books/{id}&#39;, &#39;Api\BookController@updateBook&#39;);<br>Route::delete(&#39;books/{id}&#39;,&#39;Api\BookController@deleteBook&#39;);</pre><p>Now we are ready to test these.</p><h4>Test the endpoints</h4><p>Open postman and test the endpoints.</p><p>Prefix the URLs with /api/</p><p>Example, for creating a book:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RxRWW8UHpzH_nP6s.png" /></figure><p>Example for retrieving all books:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4iPIuSWvxN729KAk.png" /></figure><p>Similarly you can test other endpoints.</p><h4>Step 4</h4><p><strong>Authenticated requests</strong></p><p><em>Note — If you do not have authentication set up in your project, you can follow </em><a href="https://fabcoding.com/laravel-rest-api-1-authentication/"><em>this</em></a><em> article for that.</em></p><p>Most of the times, you will want to secure your endpoints to that they can only be accessed with a valid access token by a logged-in user. Open the routes file and Simply wrap all the routes in the middleware like this.</p><p><strong><em>routes/api.php</em></strong></p><pre>Route::group([&#39;middleware&#39; =&gt; &#39;auth:api&#39;], function() {<br>  //routes here<br>});</pre><p>Test again using the access token obtained from authentication. You must add the token in <strong><em>Headers </em></strong>with the key <strong><em>Authorization</em></strong> and the value as <strong><em>Bearer &lt;Your token&gt;</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6OPhZe442S7fT_eI.png" /></figure><p>This way, without authorization, your endpoint cannot be used.</p><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/laravel-rest-api-2-crud-operations/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ca4ef743440" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/laravel-rest-api-2-crud-operations-2ca4ef743440">Laravel REST API — 2. CRUD Operations</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel REST API — 1. Authentication]]></title>
            <link>https://medium.com/fabcoding/laravel-rest-api-1-authentication-1a1292d229b?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a1292d229b</guid>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 15:13:21 GMT</pubDate>
            <atom:updated>2020-08-07T15:13:22.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lFa8U77QWJLjghyx.png" /></figure><blockquote>Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.</blockquote><p>If you are new to Laravel, I suggest you go through <a href="https://fabcoding.com/set-up-laravel-homestead-on-mac-step-by-step/">this article</a> first to learn how to set up and create a new project.</p><p>Once you have a project, you can continue below.</p><h4>Step 1</h4><p><strong>Install Passport</strong></p><p>In your laravel project, run the command</p><pre>composer require laravel/passport</pre><p>and then run migrate command to create all the necessary tables.</p><pre>php artisan migrate</pre><p>Finally, install it</p><pre>php artisan passport:install</pre><p>This command will create the encryption keys needed to generate secure access tokens.</p><h4>Step 2</h4><p><strong>Configure Project</strong></p><p>We will make changes in the following 3 files:</p><p><strong>1.</strong> <strong><em>app/User.php</em></strong></p><p>Add the following line at the top</p><pre>use Laravel\Passport\HasApiTokens;</pre><p>And inside the class add this usage of <strong>HasApiTokens</strong>;</p><p>The user class should now look like this</p><pre>&lt;?php<br><br>namespace App;<br><br>use Illuminate\Contracts\Auth\MustVerifyEmail;<br>use Illuminate\Foundation\Auth\User as Authenticatable;<br>use Illuminate\Notifications\Notifiable;<br><strong>use Laravel\Passport\HasApiTokens;</strong><br><br>class User extends Authenticatable {<br>  use <strong>HasApiTokens</strong>, Notifiable;<br>  ...//more code<br>}</pre><p>2. <strong>app/Providers/AuthServiceProvider.php</strong></p><p>Here we need to add Passport routes in the boot() function. Make the following changes which are in bold.</p><pre>&lt;?php<br><br>namespace App\Providers;<br><br>use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;<br>use Illuminate\Support\Facades\Gate;<br><strong>use Laravel\Passport\Passport;</strong><br><br>class AuthServiceProvider extends ServiceProvider {<br>  ... //more code<br><br>  public function boot() {<br>    $this-&gt;registerPolicies();<br><strong>    Passport::routes();</strong><br>  }<br>}</pre><p>This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens.</p><p>3. <strong>config/auth.php</strong></p><p>Here, set the driver option of the api authentication guard to passport.</p><pre>&#39;guards&#39; =&gt; [<br>  &#39;web&#39; =&gt; [<br>    &#39;driver&#39; =&gt; &#39;session&#39;,<br>    &#39;provider&#39; =&gt; &#39;users&#39;,<br>  ],<br><br>  &#39;api&#39; =&gt; [<br><strong>    &#39;driver&#39; =&gt; &#39;passport&#39;,</strong><br>    &#39;provider&#39; =&gt; &#39;users&#39;,<br>    &#39;hash&#39; =&gt; false,<br>  ],<br>],</pre><h4>Step 3</h4><p><strong>The controller</strong></p><p>Now we will make the controller for handling the logic of the authentication routes. Run the following command to create a controller, We shall create this inside a new namespace for the Api, so that all your API controllers can be separate for cleaner architecture.</p><pre>php artisan make:controller Api/AuthController</pre><p>Go to the newly created file in <strong><em>app/Http/Controllers/Api/AuthController.php</em></strong></p><pre>&lt;?php<br><br>namespace App\Http\Controllers\Api;<br><br>use App\Http\Controllers\Controller;<br>use Illuminate\Http\Request;<br>use Illuminate\Support\Facades\Auth;<br>use Carbon\Carbon;<br>use App\User;<br><br>class AuthController extends Controller<br>{<br><br>}</pre><p>Add the methods for login, register, logout and one for getting the user detail</p><pre>public function register(Request $request) {<br>  $validatedData = $request-&gt;validate([<br>    &#39;name&#39; =&gt; &#39;required|max:55&#39;,<br>    &#39;role&#39; =&gt; &#39;required|max:55&#39;,<br>    &#39;email&#39; =&gt; &#39;email|required|unique:users&#39;,<br>    &#39;password&#39; =&gt; &#39;required|confirmed&#39;<br>  ]);<br><br>  $validatedData[&#39;password&#39;] = bcrypt($request-&gt;password);<br>  $user = User::create($validatedData);<br>  $accessToken = $user-&gt;createToken(&#39;authToken&#39;)-&gt;accessToken;<br><br>  return response([ &#39;user&#39; =&gt; $user, &#39;access_token&#39; =&gt; $accessToken]);<br>}<br><br>public function login(Request $request) {<br>  $loginData = $request-&gt;validate([<br>    &#39;email&#39; =&gt; &#39;email|required&#39;,<br>    &#39;password&#39; =&gt; &#39;required&#39;<br>  ]);<br>  <br>  if (!auth()-&gt;attempt($loginData)) {<br>    return response([&#39;message&#39; =&gt; &#39;Invalid Credentials&#39;]);<br>  }<br> <br>  $accessToken = auth()-&gt;user()-&gt;createToken(&#39;authToken&#39;)-&gt;accessToken;<br>  return response([&#39;user&#39; =&gt; auth()-&gt;user(), &#39;access_token&#39; =&gt; $accessToken]);<br>}<br><br>public function logout(Request $request) {<br>  $request-&gt;user()-&gt;token()-&gt;revoke();<br>  return response()-&gt;json([<br>    &#39;message&#39; =&gt; &#39;Successfully logged out&#39;<br>  ]);<br>}<br><br>public function user(Request $request) {. <br>  return response()-&gt;json($request-&gt;user());<br>}</pre><h4>Step 4</h4><p><strong>The routes</strong></p><p>Now the last step is to configure the routes for accessing the api functions.</p><p>Go to <strong><em>routes/api.php</em></strong> file and add the following routes, for each of the functions we wrote in our controller.</p><pre>Route::post(&#39;/register&#39;, &#39;Api\AuthController@register&#39;);<br>Route::post(&#39;/login&#39;, &#39;Api\AuthController@login&#39;);<br>Route::post(&#39;/logout&#39;, &#39;Api\AuthController@logout&#39;);</pre><p>Now you are ready to test your api!</p><h4>Test</h4><p>Open Postman and test the endpoints.</p><pre>POST <a href="http://localhost:8000/api/login">http://localhost:8000/api/login</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Djz8c6FWyn7twgAg.png" /></figure><p>Similarly, you can pass the parameters for the <em>register</em> endpoint and test it.</p><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/laravel-rest-api-1-authentication/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a1292d229b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/laravel-rest-api-1-authentication-1a1292d229b">Laravel REST API — 1. Authentication</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom Start-and-End Time Picker Alert in Swift]]></title>
            <link>https://medium.com/fabcoding/create-a-custom-start-and-end-time-picker-alert-in-swift-301dd26e6c86?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/301dd26e6c86</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 11:50:25 GMT</pubDate>
            <atom:updated>2020-08-05T11:50:26.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*6pH77nb5QjqhNh-L.png" /></figure><p>This tutorial is concise and assumes that you already know how to add constraints, connect outlets, and create delegates.</p><p>Leave a comment below if you are a beginner and need assistance with these!</p><h4>Design</h4><p>First let us design the alert view.</p><p>Drag a <em>ViewController</em> on to your storyboard.</p><p>Add a <em>view</em>, add necessary <em>constraints</em>, <em>header labels</em> and the most important part — a <em>UIPickerView</em>. Also add <em>OK</em> and <em>Cancel</em> <em>buttons</em> at the bottom. Here’s how my view looks after design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/0*WRKg6de8fHX1KOnp.png" /></figure><h4>Code</h4><p>Now create a Swift class for this ViewController that we created, named <strong>MyTimePickerAlert.swift</strong>. We also need to create a <strong>Delegate</strong> for this, so that we can communicate data back to our main view controller from where we will be presenting this alert.</p><p>So here’s the initial code for the file <strong>MyTimePickerAlert.swift</strong>.</p><pre>import UIKit<br><br>protocol MyTimePickerAlertDelegate: class {<br>    func pickerAlertSelected(t1: String, t2: String)<br>    func pickerAlertCancel()<br>}<br><br>class MyTimePickerAlert: UIViewController {<br><br>}</pre><p>Now, inside the class <em>MyTimePickerAlert</em>, declare outlets for our significant views.</p><pre>@IBOutlet weak var alertView: UIView!<br>    @IBOutlet weak var cancelButton: UIButton!<br>    @IBOutlet weak var okButton: UIButton!<br>    @IBOutlet weak var pickerView: UIPickerView!</pre><p>also declare a variable for the delegate</p><pre>var delegate: MyTimePickerAlertDelegate?</pre><p>Also, declare arrays to store the start and end times, and a dateformatter instance that will be used for formatting the times.</p><pre>var startTimes = [String]()<br>    var endTimes = [String]()<br>    let timeFormatter = DateFormatter()</pre><p>Let us write a function to get a list of all the time values. We shall also pass a parameter to determine the offset for the end times; because we do not want the user to be able to select an END time that is earlier than the START time.</p><pre>extension MyTimePickerAlert {<br>    func getTimeList(from: Int) -&gt; [String] {<br>        let alllist: [String] = [<br>            &quot;1:00 AM&quot;,&quot;2:00 AM&quot;,&quot;3:00 AM&quot;,&quot;4:00 AM&quot;,&quot;5:00 AM&quot;, &quot;6:00 AM&quot;, &quot;7:00 AM&quot;, &quot;8:00 AM&quot;, &quot;9:00 AM&quot;,&quot;10:00 AM&quot;,&quot;11:00 AM&quot;, &quot;12:00 PM&quot;, &quot;1:00 PM&quot;, &quot;2:00 PM&quot;, &quot;3:00 PM&quot;, &quot;4:00 PM&quot;, &quot;5:00 PM&quot;, &quot;6:00 PM&quot;, &quot;7:00 PM&quot;, &quot;8:00 PM&quot;, &quot;9:00 PM&quot;, &quot;10:00 PM&quot;, &quot;11:00 PM&quot;, &quot;12:00 AM&quot;]<br>        var list: [String] = []<br>        for i in from...alllist.count-1 {<br>            list.append(alllist[i])<br>        }<br>        return list   <br>    }<br>}</pre><p>Now write the delegate and datasource methods for populating the data of the PickerView.</p><pre>extension MyTimePickerAlert: UIPickerViewDelegate, UIPickerViewDataSource {<br><br>    func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {<br>        return 2<br>    }<br>   <br>    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int {<br>        switch component {<br>           <br>        case 0:<br>            return startTimes.count<br>        case 1:<br>            return endTimes.count<br>        default:<br>            return 0<br>        }<br>    }<br>   <br>    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -&gt; UIView {<br>        var label: UILabel<br>       <br>        if let view = view as? UILabel {<br>            label = view<br>        } else {<br>            label = UILabel()<br>        }<br>       <br>        label.textColor = .black<br>        label.textAlignment = .center<br>        label.font = UIFont.systemFont(ofSize: 15)<br>       <br>        var text = &quot;&quot;<br>       <br>        switch component {<br>        case 0:<br>            text = startTimes[row]<br>        case 1:<br>            text = endTimes[row]<br>        default:<br>            break<br>        }<br>       <br>        label.text = text<br>       <br>        return label<br>    }<br>   <br>    //this is for reloading the END times list, according to the value selected as the START time.<br>    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {<br>        if (component == 0) {<br>           <br>            endTimes = getTimeList(from: row)<br>            pickerView.reloadComponent(1)<br>        }<br>       <br>    }<br>}</pre><p>And, let us initialise the views and set the button actions; and call the delegate function upon user selecting OK.</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        pickerView.delegate = self<br>        pickerView.dataSource = self<br>        <br>        timeFormatter.timeStyle = .short<br>        startTimes = getTimeList(from: 0)<br>        endTimes = getTimeList(from: 0)<br>        <br>        cancelButton.addTarget(self, action: #selector(cancelMe), for: .touchUpInside)<br>        okButton.addTarget(self, action: #selector(okMe), for: .touchUpInside)<br>        <br>    }<br>   <br>    @objc func okMe() {<br>        delegate?.pickerAlertSelected(t1: startTimes[pickerView.selectedRow(inComponent: 0)], t2: endTimes[pickerView.selectedRow(inComponent: 1)])<br>        self.dismiss(animated: true, completion: nil)<br>    }<br>    <br>    @objc func cancelMe() {<br>        delegate?.pickerAlertCancel()<br>        self.dismiss(animated: true, completion: nil)<br>    }</pre><p>Go back to your storyboard, find the view controller that we designed for the alert, and change its class to <strong><em>MyTimePickerAlert</em></strong>, and also set storyboard ID as <strong><em>mytimepicker</em></strong> (or anything you like).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4fV8borM3jNjl8gY.png" /></figure><p>Also <strong>do not forget</strong> to <strong>connect all the IBOutlets</strong> to their respective views.</p><p>Finally, go to the main <strong><em>ViewController</em></strong> class — the screen from where you wish to launch the Picker Alert view and add this code to present the alert view and to handle the actions of OK or Cancel buttons.</p><pre>extension ViewController: MyTimePickerAlertDelegate {<br><br>    @objc func showTimePicker() {<br>        let customAlert = self.storyboard?.instantiateViewController(withIdentifier: &quot;mytimepicker&quot;) as! MyTimePickerAlert<br>        customAlert.providesPresentationContextTransitionStyle = true<br>        customAlert.definesPresentationContext = true<br>        customAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext<br>        customAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve<br>        customAlert.delegate = self<br>        self.present(customAlert, animated: true, completion: nil)<br>    }<br><br>    func pickerAlertCancel() {<br><br>    }<br><br>    func pickerAlertSelected(t1: String, t2: String) {<br>        //Do something with the selected times, display it somewhere<br>        print(&quot;START time is \(t1) and END time is \(t2)&quot;)<br>    }<br>}</pre><p>Now just call the function showTimePicker() from any button or textfield click.</p><pre>showTimePicker()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*5AcMwG3k9iHIjbwk.png" /></figure><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/create-a-custom-start-and-end-time-picker-alert-in-swift/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=301dd26e6c86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/create-a-custom-start-and-end-time-picker-alert-in-swift-301dd26e6c86">Create a custom Start-and-End Time Picker Alert in Swift</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel — Redirect users according to roles, and protect routes]]></title>
            <link>https://medium.com/fabcoding/laravel-redirect-users-according-to-roles-and-protect-routes-bde324fe1823?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde324fe1823</guid>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 02:39:03 GMT</pubDate>
            <atom:updated>2020-08-07T00:29:38.989Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel — Redirect to different views based on user role</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LQEL0LbP_KyyuWTy.png" /></figure><h4>Objective</h4><blockquote><em>In this tutorial, we shall have a project named ‘</em><strong><em>mystore</em></strong><em>’, which can have 2 kinds of users, either ‘</em><strong><em>admin</em></strong><em>’ or ‘</em><strong><em>seller</em></strong><em>’. They will have separate dashboards with separate features and functionalities. When a user logs in to our website, they will be redirected to a dashboard according to their role. Also, the routes should be protected, meaning, the logged in user should not be able to access the dashboard or any of the inside pages of the other role, even if they type the URL in the browser. So let us begin.</em></blockquote><p>If you are new to Laravel, I recommend going through <a href="https://medium.com/fabcoding/set-up-laravel-homestead-on-mac-step-by-step-271a3489ff1">this</a> article, to learn how to set up Laravel and create and run Laravel projects.</p><h4>Step 1</h4><p><strong>Configuring project</strong></p><p>After creating the new Laravel project, we will run a couple of quick commands for scaffolding the authentication system.</p><pre>composer require laravel/ui<br>php artisan ui vue --auth</pre><p>and then, run this command to compile it.</p><pre>npm install &amp;&amp; npm run dev</pre><p>Now run the project in your browser, you should be able to see a working page. You should also be able to click on the LOGIN and REGISTER to go their respective forms and use them to register and login.</p><h4>Step 2</h4><p><strong>Set up users, Add role attribute to Users table</strong></p><p>We will be using a simple string attribute in the Users table to identify the role of the user. For this example, the user role can either be ‘<em>admin</em>’ or ‘<em>seller</em>’.</p><p>Go to the <em>Users</em> table migration. It will be present in a file: <strong><em>mystore/database/migrations/xxx-xxx-xxx_create_users_table.php</em></strong></p><p>Add a string column named ‘<em>role</em>’ which will store the role of the user.</p><pre>public function up() {<br>  Schema::create(&#39;users&#39;, function (Blueprint $table) {<br>    ...<br><strong>    $table-&gt;string(&#39;role&#39;);</strong><br>  });<br>}</pre><p>Run the command</p><pre>php artisan migrate</pre><p>We also need to add this new field to the registration logic.</p><p>Open <strong><em>mystore/app/Http/Controllers/Auth/RegisterController.php</em></strong><em> </em>file. Add a line for the new column in both the <em>validator</em> and the <em>create</em> methods.</p><pre>protected function validator(array $data) {<br>  return Validator::make($data, [<br>    ...<br>    &#39;role&#39; =&gt; [&#39;required&#39;, &#39;string&#39;, &#39;max:255&#39;],<br>  ]);<br>}<br><br>protected function create(array $data) {<br>  return User::create([<br>    ...<br>    &#39;role&#39; =&gt; $data[&#39;role&#39;],<br>  ]);<br>}</pre><p>Now let us create 2 users, one for each of our roles: <em>admin</em> and <em>seller</em>. We will do this using seeds. Run the following command to create a seeder</p><pre>php artisan make:seeder UsersTableSeeder</pre><p>check <strong><em>mystore/database/seeds</em></strong> for the newly created file <strong><em>UsersTableSeeder.php</em></strong></p><p>Replace the run() method with the following</p><pre>public function run() {<br>  DB::table(&#39;users&#39;)-&gt;truncate(); //for cleaning earlier data to avoid duplicate entries<br>  DB::table(&#39;users&#39;)-&gt;insert([<br>    &#39;name&#39; =&gt; &#39;the admin user&#39;,<br>    &#39;email&#39; =&gt; &#39;iamadmin@gmail.com&#39;,<br>    &#39;role&#39; =&gt; &#39;admin&#39;,<br>    &#39;password&#39; =&gt; Hash::make(&#39;password&#39;),<br>  ]);<br>  DB::table(&#39;users&#39;)-&gt;insert([<br>    &#39;name&#39; =&gt; &#39;the seller user&#39;,<br>    &#39;email&#39; =&gt; &#39;iamaseller@gmail.com&#39;,<br>    &#39;role&#39; =&gt; &#39;seller&#39;,<br>    &#39;password&#39; =&gt; Hash::make(&#39;password&#39;),<br>  ]);<br>}</pre><p>In the same folder, open DatabaseSeeder.php file, and inside the run() method, add the call to our new seeder.</p><pre>$this-&gt;call(UsersTableSeeder::class);</pre><p>Now run the commands</p><pre>composer dump-autoload<br>php artisan db:seed</pre><p>Now you can test the login using these newly created account credentials</p><h4>Step 3</h4><p><strong>Create 2 separate dashboards and routes</strong></p><p>Go to <em>mystore/resources/views. </em>Create 2 folders named <em>admin</em> and <em>seller</em> and create a file <strong><em>dashboard.blade.php</em></strong> inside each of these. Let us populate with some basic content for distinction.</p><p><strong><em>admin/dashboard.blade.php</em></strong></p><pre>@extends(&#39;layouts.app&#39;)<br><br>@section(&#39;content&#39;)<br>&lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;row justify-content-center&quot;&gt;<br>        &lt;div class=&quot;col-md-8&quot;&gt;<br>            &lt;div class=&quot;card&quot;&gt;<br>                &lt;div class=&quot;card-header&quot;&gt;{{ __(&#39;Dashboard&#39;) }}&lt;/div&gt;<br><br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    @if (session(&#39;status&#39;))<br>                        &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                            {{ session(&#39;status&#39;) }}<br>                        &lt;/div&gt;<br>                    @endif<br><br>                    {{ __(&#39;Hello ADMINISTRATOR, You are logged in!&#39;) }}<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br>@endsection</pre><p><strong><em>seller/dashboard.blade.php</em></strong></p><pre>@extends(&#39;layouts.app&#39;)<br><br>@section(&#39;content&#39;)<br>&lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;row justify-content-center&quot;&gt;<br>        &lt;div class=&quot;col-md-8&quot;&gt;<br>            &lt;div class=&quot;card&quot;&gt;<br>                &lt;div class=&quot;card-header&quot;&gt;{{ __(&#39;Dashboard&#39;) }}&lt;/div&gt;<br><br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    @if (session(&#39;status&#39;))<br>                        &lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                            {{ session(&#39;status&#39;) }}<br>                        &lt;/div&gt;<br>                    @endif<br><br>                    {{ __(&#39;Hello SELLER, You are logged in!&#39;) }}<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br>@endsection</pre><p>Also, to create controllers, run the following commands</p><pre>php artisan make:controller Admin/DashboardController<br>php artisan make:controller Seller/DashboardController</pre><p>Go to the newly created files under <strong><em>mystore/app/Http/Controllers</em></strong><em> </em>and modify them to return the views that we created above.</p><p><strong><em>Admin/DashboardController.php</em></strong></p><pre>&lt;?php<br>namespace App\Http\Controllers\Admin;<br>use App\Http\Controllers\Controller;<br>use Illuminate\Http\Request;<br><br>class DashboardController extends Controller {<br>  public function __construct() {<br>    $this-&gt;middleware(&#39;auth&#39;);<br>  }<br>  public function index() {<br>    return view(&#39;admin.dashboard&#39;);<br>  }<br>}</pre><p><strong><em>Seller/DashboardController.php</em></strong></p><pre>&lt;?php<br>namespace App\Http\Controllers\Seller;<br>use App\Http\Controllers\Controller;<br>use Illuminate\Http\Request;<br><br>class DashboardController extends Controller {<br>  public function __construct() {<br>    $this-&gt;middleware(&#39;auth&#39;);<br>  }<br>  public function index() {<br>    return view(&#39;seller.dashboard&#39;);<br>  }<br>}</pre><p>Now create routes for these 2 dashboards.</p><p>Go to <em>mystore/routes/web.php</em> file and add the following.</p><pre>Route::get(&#39;/admin_dashboard&#39;, &#39;Admin\DashboardController@index&#39;);<br>Route::get(&#39;/seller_dashboard&#39;, &#39;Seller\DashboardController@index&#39;);</pre><p>Now you can open your browser and try the urls with the above routes, and you should see the two distinct skeleton dashboards.</p><h4>Step 4</h4><p><strong>Redirect during login</strong></p><p>Lets now write the login to check the user role during login and redirect the user to the respective dashbaord.</p><p>Go to <strong><em>mystore/app/Http/Controllers/Auth/LoginController.php</em></strong> file.</p><p>Find the redirect method</p><pre>protected $redirectTo = RouteServiceProvider::HOME;</pre><p>Remove this line and replace it with the below function which checks role and returns route.</p><pre>public function redirectTo() {<br>  $role = Auth::user()-&gt;role; <br>  switch ($role) {<br>    case &#39;admin&#39;:<br>      return &#39;/admin_dashboard&#39;;<br>      break;<br>    case &#39;seller&#39;:<br>      return &#39;/seller_dashboard&#39;;<br>      break; <br><br>    default:<br>      return &#39;/home&#39;; <br>    break;<br>  }<br>}</pre><p>Make sure to include this line at the top, since we are using Auth.</p><pre>use Illuminate\Support\Facades\Auth;</pre><p>Also apply the same conditional logic to another file, <strong><em>app/Http/Middleware/RedirectIfAuthenticated.php</em></strong>. Change the handle() method to the following:</p><pre>public function handle($request, Closure $next, $guard = null) {<br>  if (Auth::guard($guard)-&gt;check()) {<br>    $role = Auth::user()-&gt;role; <br><br>    switch ($role) {<br>      case &#39;admin&#39;:<br>         return redirect(&#39;/admin_dashboard&#39;);<br>         break;<br>      case &#39;seller&#39;:<br>         return redirect(&#39;/seller_dashboard&#39;);<br>         break; <br><br>      default:<br>         return redirect(&#39;/home&#39;); <br>         break;<br>    }<br>  }<br>  return $next($request);<br>}</pre><p>And you’re done. You can now go to your browser, and try logging in with the admin and seller accounts, and you will be redirected to the respective dashboards.</p><h4>Step 5</h4><p><strong>Protect the routes</strong></p><p>For now, if you are logged in as a seller, and you type the admin dashboard route URL in your browser, it works! This is not ideal. We need to protect the routes using a middleware.</p><p>In the folder <strong><em>mystore/app/Http/Middleware</em></strong> create a new file<strong><em> Role.php</em></strong>, and add the following code for role check</p><pre>&lt;?php<br><br>namespace App\Http\Middleware;<br>use Closure;<br>use Illuminate\Auth\Middleware\Role as Middleware;<br>use Illuminate\Support\Facades\Auth;<br><br>class Role {<br><br>  public function handle($request, Closure $next, String $role) {<br>    if (!Auth::check()) // This isnt necessary, it should be part of your &#39;auth&#39; middleware<br>      return redirect(&#39;/home&#39;);<br><br>    $user = Auth::user();<br>    if($user-&gt;role == $role)<br>      return $next($request);<br><br>    return redirect(&#39;/home&#39;);<br>  }<br>}</pre><p>In case, you want to support multiple roles for a different kind of application, you would pass an array of roles and use <em>foreach</em> to loop through them and check.</p><p>Go to <strong><em>app/Http/Kernel.php</em></strong> file and add this middleware to the <em>routeMiddleware</em> array</p><pre>protected $routeMiddleware = [<br>  ...<br>  &#39;role&#39; =&gt; \App\Http\Middleware\Role::class,<br>];</pre><p>Now let us apply this middleware to our routes. Go back to the <strong><em>mystore/routes/web.php</em></strong> file and modify the route definitions.</p><pre>Route::get(&#39;/admin_dashboard&#39;, &#39;Admin\DashboardController@index&#39;)-&gt;middleware(&#39;role:admin&#39;);<br>Route::get(&#39;/seller_dashboard&#39;, &#39;Seller\DashboardController@index&#39;)-&gt;middleware(&#39;role:seller&#39;);</pre><p>That’s it! Now go back to your browser, log in as seller role and try opening the dashboard of the admin role (and vice versa), it should redirect to the given route that is /home.</p><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/laravel-redirect-users-according-to-roles-and-protect-routes/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde324fe1823" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/laravel-redirect-users-according-to-roles-and-protect-routes-bde324fe1823">Laravel — Redirect users according to roles, and protect routes</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter — Hide / show AppBar while scrolling]]></title>
            <link>https://medium.com/fabcoding/flutter-hide-show-appbar-while-scrolling-e3c2664b675d?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3c2664b675d</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 23:23:17 GMT</pubDate>
            <atom:updated>2020-08-03T23:23:20.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6uzIENcSYlV0Rz9.png" /></figure><h4>Showing the AppBar as soon as you begin scrolling upward</h4><p>The <em>SliverAppBar</em> provided by Flutter, supports a floating app bar that hides upon scrolling down. <strong>But</strong> there’s one downside about it, <em>it reappears only when the user scrolls back up all way to the top</em> of the scroll view. This can be undesirable if the scroll content happens to be larger. For example in the Medium app, the <strong>app bar shows up as soon as you start scrolling upward,</strong> no matter where you are. This is what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/0*mK4pST2f5zDKBBPv.gif" /></figure><p>So in this tutorial we will implement this action using <em>ScrollController</em> and <em>AnimatedContainer</em>.</p><p>Let us begin by creating a simple screen, a stateful widget.</p><pre>class HomeScreen extends StatefulWidget {<br>  @override<br>  _HomeScreenState createState() =&gt; _HomeScreenState();<br>}<br><br>class _HomeScreenState extends State&lt;HomeScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Container();<br>  }<br>}</pre><p>Inside the state class, declare a scroll controller; and two variables to hold the current action/state.</p><pre>ScrollController _scrollViewController;<br>bool _showAppbar = true; <br>bool isScrollingDown = false;</pre><p>In the state initialization method, arrach a listener to the <em>ScrollController </em>and define its action to detect the scroll direction and accordingly set the value of the variable which will be used to determine the visibility of the app bar.</p><pre>@override<br>void initState() {<br>  super.initState();<br>  _scrollViewController = new ScrollController();<br>  _scrollViewController.addListener(() {<br>    if (_scrollViewController.position.userScrollDirection == ScrollDirection.reverse) {<br>      if (!isScrollingDown) {<br>        isScrollingDown = true;<br>        _showAppbar = false;<br>        setState(() {});<br>      }<br>    }<br><br>    if (_scrollViewController.position.userScrollDirection == ScrollDirection.forward) {<br>      if (isScrollingDown) {<br>        isScrollingDown = false;<br>        _showAppbar = true;<br>        setState(() {});<br>      }<br>    }<br>  });<br>}</pre><p>Don’t forget to dispose the controller!</p><pre>@override<br>void dispose() {<br>  _scrollViewController.dispose();<br>  _scrollViewController.removeListener(() {});<br>  super.dispose();<br>}</pre><p>Now create the screen view in the build method.</p><pre>@override<br>Widget build(BuildContext context) {<br><br>return Scaffold(<br>  body: SafeArea(<br>    child: Column(<br>      children: &lt;Widget&gt;[<br>        AnimatedContainer(<br>          height: _showAppbar ? 56.0 : 0.0,<br>          duration: Duration(milliseconds: 200),<br>            child: AppBar(<br>              title: Text(&#39;Scroll Demo&#39;),<br>              actions: &lt;Widget&gt;[<br>                //add buttons here<br>              ],<br>            ),<br>          ),<br><br>          Expanded(<br>            child: SingleChildScrollView(<br>              controller: _scrollViewController,<br>              child: Column(<br>                children: &lt;Widget&gt;[<br>                  //add your screen content here<br>                ],<br>              ),<br>            ),<br>          ),<br><br>        ],<br>      ),<br>    ),<br>  );<br>}</pre><p>As you can see, our screen is a simple <em>Column</em> widget, with the <em>AppBar</em> wrapped in an <em>AnimatedCnotainer</em>, and a <em>SingleChildScrollView</em> in the rest of the area.</p><p>The <em>AppBar</em> is wrapped in <em>AnimatedContainer</em> in order to animate the hide and show transitions.</p><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/flutter-hide-show-appbar-while-scrolling/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3c2664b675d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/flutter-hide-show-appbar-while-scrolling-e3c2664b675d">Flutter — Hide / show AppBar while scrolling</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Display route between 2 locations using MapKit]]></title>
            <link>https://medium.com/fabcoding/swift-display-route-between-2-locations-using-mapkit-7de8ee0acd38?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de8ee0acd38</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 22:17:34 GMT</pubDate>
            <atom:updated>2020-08-03T22:17:37.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*81BehllF20s9ETfu.jpg" /></figure><p>Apple’s MapKit makes it very easy to get directions from one coordinate to another. Let us see how to use this to show a route on an MKMapView.</p><p><strong>First</strong>, make the <em>ViewController</em> conform to the <strong>MKMapViewDelegate</strong> protocol.</p><p>and make sure the outlet of the map view is attached and the delegate is set.</p><pre>mapView.delegate = self</pre><p>Now write this method for showing the route. This method performs the following actions</p><ol><li>Takes 2 coordinates as parameters</li><li>Fetches direction between the 2 points</li><li>Displays the fetched route on the map</li><li>Zooms the map to the route area.</li></ol><pre>func showRouteOnMap(pickupCoordinate: CLLocationCoordinate2D, destinationCoordinate: CLLocationCoordinate2D) {<br><br>        let request = MKDirections.Request()<br>        request.source = MKMapItem(placemark: MKPlacemark(coordinate: pickupCoordinate, addressDictionary: nil))<br>        request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destinationCoordinate, addressDictionary: nil))<br>        request.requestsAlternateRoutes = true<br>        request.transportType = .automobile<br><br>        let directions = MKDirections(request: request)<br><br>        directions.calculate { [unowned self] response, error in<br>            guard let unwrappedResponse = response else { return }<br>            <br>            //for getting just one route<br>            if let route = unwrappedResponse.routes.first {<br>                //show on map<br>                self.mapView.addOverlay(route.polyline)<br>                //set the map area to show the route<br>                self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets.init(top: 80.0, left: 20.0, bottom: 100.0, right: 20.0), animated: true)<br>            }<br><br>            //if you want to show multiple routes then you can get all routes in a loop in the following statement<br>            //for route in unwrappedResponse.routes {}<br>        }<br>    }</pre><p>Also, write the following delegate function to render the line showing the route. This can be customised in color and width according to your preference.</p><pre>//this delegate function is for displaying the route overlay and styling it        <br>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -&gt; MKOverlayRenderer {<br>     let renderer = MKPolylineRenderer(overlay: overlay)<br>     renderer.strokeColor = UIColor.red<br>     renderer.lineWidth = 5.0<br>     return renderer     <br>}</pre><p>Now, let us call this with some sample coordinates from our <em>viewDidLoad</em> method.</p><pre>//create two dummy locations<br>let loc1 = CLLocationCoordinate2D.init(latitude: 40.741895, longitude: -73.989308)<br>let loc2 = CLLocationCoordinate2D.init(latitude: 40.728448, longitude: -73.717996)<br><br>//find route<br>showRouteOnMap(pickupCoordinate: loc1, destinationCoordinate: loc2)</pre><p>You should be able to see a route on the map now!</p><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/swift-display-route-between-2-locations-using-mapkit/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de8ee0acd38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/swift-display-route-between-2-locations-using-mapkit-7de8ee0acd38">Swift — Display route between 2 locations using MapKit</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift — Display route between two coordinates on Google Map / GMSMapView, using MapKit —…]]></title>
            <link>https://medium.com/fabcoding/swift-display-route-between-two-coordinates-on-google-map-gmsmapview-using-mapkit-c4f31bc43a8d?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4f31bc43a8d</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 16:41:58 GMT</pubDate>
            <atom:updated>2020-08-03T16:42:02.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift — Display route between two coordinates on Google Map / GMSMapView, using MapKit — MKDirections</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HXsPNa7QFSQPBgev.png" /></figure><p>This tutorial shows, in a Swift app, how we can use <em>MapKit’s</em> free direction service <em>MKDirections</em>, to get a route between two coordinates and show the resulting route on a Google Map, <em>GMSMapView</em>.</p><p><strong>First</strong>, get this file, and save it within your project as <em>Polyline.swift. </em>This will be used to create Polyline from coordinates:</p><p><a href="https://github.com/raphaelmor/Polyline/blob/master/Sources/Polyline/Polyline.swift">raphaelmor/Polyline</a></p><p><strong>Second</strong>, use the two coordinates and pin markers on the points.</p><pre>import UIKit<br>import GoogleMaps <br>import MapKit<br>func setMapMarkersRoute(vLoc: CLLocationCoordinate2D, toLoc: CLLocationCoordinate2D) {<br><br>    //add the markers for the 2 locations<br>    let markerTo = GMSMarker.init(position: toLoc)<br>    markerTo.map = mapView<br>    let vMarker = GMSMarker.init(position: vLoc)<br>    vMarker.map = mapView<br><br>    //zoom the map to show the desired area<br>    var bounds = GMSCoordinateBounds()<br>    bounds = bounds.includingCoordinate(vLoc)<br>    bounds = bounds.includingCoordinate(toLoc)<br>    self.mapView.moveCamera(GMSCameraUpdate.fit(bounds))<br><br>    //finally get the route<br>    getRoute(from: vLoc, to: toLoc)<br><br>}</pre><p><strong>Third</strong>, the function to get the directions using MKDirections</p><pre>func getRoute(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) {<br>    <br>    let source = MKMapItem(placemark: MKPlacemark(coordinate: from))<br>    let destination = MKMapItem(placemark: MKPlacemark(coordinate: to))<br><br>    let request = MKDirections.Request()<br>    request.source = source<br>    request.destination = destination<br>    request.requestsAlternateRoutes = false<br><br>    let directions = MKDirections(request: request)<br><br>    directions.calculate(completionHandler: { (response, error) in<br>        if let res = response {<br>            //the function to convert the result and show<br>            self.show(polyline: self.googlePolylines(from: res))<br>        }<br>    })<br>}</pre><p><strong>Fourth</strong>, converting the result from <em>MKDirections</em>, to <em>GMSPolyline</em>, that can be used with <em>GMSMapView</em></p><pre>private func googlePolylines(from response: MKDirections.Response) -&gt; GMSPolyline {<br><br>    let route = response.routes[0]<br>    var coordinates = [CLLocationCoordinate2D](<br>        repeating: kCLLocationCoordinate2DInvalid,<br>        count: route.polyline.pointCount)<br><br>    route.polyline.getCoordinates(<br>        &amp;coordinates,<br>        range: NSRange(location: 0, length: route.polyline.pointCount))<br><br>    let polyline = Polyline(coordinates: coordinates)<br>    let encodedPolyline: String = polyline.encodedPolyline<br>    let path = GMSPath(fromEncodedPath: encodedPolyline)<br>    return GMSPolyline(path: path)<br>    <br>}</pre><p><strong>Fifth</strong>, finally show it on the <em>GMSMapView</em></p><pre>func show(polyline: GMSPolyline) {<br><br>    //add style to polyline<br>    polyline.strokeColor = UIColor.red<br>    polyline.strokeWidth = 3<br>    <br>    //add to map<br>    polyline.map = mapView<br>}</pre><p>Make sure you have created an outlet to the <em>GMSMapView</em>.</p><p>Hope this helps. If you need assistance, feel free to leave a comment!</p><p><em>Originally published at </em><a href="http://fabcoding.com/swift-display-route-between-two-coordinates-on-google-map-gmsmapview-using-mapkit-mkdirections/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4f31bc43a8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/swift-display-route-between-two-coordinates-on-google-map-gmsmapview-using-mapkit-c4f31bc43a8d">Swift — Display route between two coordinates on Google Map / GMSMapView, using MapKit —…</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding an Image Picker in a Flutter App — Pick images using Camera and Gallery / Photos]]></title>
            <link>https://medium.com/fabcoding/adding-an-image-picker-in-a-flutter-app-pick-images-using-camera-and-gallery-photos-7f016365d856?source=rss-8b5b553ede78------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f016365d856</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Zeba Rahman]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 01:11:50 GMT</pubDate>
            <atom:updated>2020-06-08T01:11:52.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*GXG6b6rEnhp--RZJ.png" /></figure><p>Image Picker is a common component we often need for user-profiles and other stuff. We will be using this <a href="https://pub.dev/packages/image_picker">plugin</a> by Flutter developers.</p><h4>Step 1 — Add the dependency to your <em>pubspec.yaml</em> file.</h4><pre>image_picker: ^0.6.6+5</pre><h4>Step 2 — Configure native platforms</h4><p>Next, we need to configure native settings. For the Android platform, nothing is needed. For iOS, open Info.plist file found under ios/Runner folder and add the following keys.</p><pre>&lt;key&gt;NSPhotoLibraryUsageDescription&lt;/key&gt;<br>&lt;string&gt;Allow access to photo library&lt;/string&gt;<br><br>&lt;key&gt;NSCameraUsageDescription&lt;/key&gt;<br>&lt;string&gt;Allow access to camera to capture photos&lt;/string&gt;<br><br>&lt;key&gt;NSMicrophoneUsageDescription&lt;/key&gt;<br>&lt;string&gt;Allow access to microphone&lt;/string&gt;</pre><h4>Step 3 — Image Picker function</h4><p>In our screen’s StatefulWidget’s State class, declare a File variable to hold the image picked by the user.</p><pre>File _image;</pre><p>Now write two functions for picking image via Camera and Photo Library respectively. The optional parameter imageQuality accepts any value between 0and 100, you can adjust it according to the size and quality required by your app. After obtaining the image file, we save it into the _image variable and call setState() so that it can be displayed in the screen.</p><pre>_imgFromCamera() async {<br>  File image = await ImagePicker.pickImage(<br>    source: ImageSource.camera, imageQuality: 50<br>  );<br><br>  setState(() {<br>    _image = image;<br>  });<br>}<br><br>_imgFromGallery() async {<br>  File image = await  ImagePicker.pickImage(<br>      source: ImageSource.gallery, imageQuality: 50<br>  );<br><br>  setState(() {<br>    _image = image;<br>  });<br>}</pre><h4>Step 4 — Create an option chooser for selecting camera / gallery</h4><p>Next, write a function for displaying a bottom sheet for the user for choosing the option of camera or gallery.</p><pre>void _showPicker(context) {<br>  showModalBottomSheet(<br>      context: context,<br>      builder: (BuildContext bc) {<br>        return SafeArea(<br>          child: Container(<br>            child: new Wrap(<br>              children: &lt;Widget&gt;[<br>                new ListTile(<br>                    leading: new Icon(Icons.photo_library),<br>                    title: new Text(&#39;Photo Library&#39;),<br>                    onTap: () {<br>                      _imgFromGallery();<br>                      Navigator.of(context).pop();<br>                    }),<br>                new ListTile(<br>                  leading: new Icon(Icons.photo_camera),<br>                  title: new Text(&#39;Camera&#39;),<br>                  onTap: () {<br>                    _imgFromCamera();<br>                    Navigator.of(context).pop();<br>                  },<br>                ),<br>              ],<br>            ),<br>          ),<br>        );<br>      }<br>    );<br>}</pre><h4>Step 5 — Create and configure the Image view on screen</h4><p>Finally, let us create a profile picture holder on the screen, which opens the chooser upon click, and displays the selected image.</p><pre>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    appBar: AppBar(),<br>    body: Column(<br>      children: &lt;Widget&gt;[<br>        SizedBox(<br>          height: 32,<br>        ),<br>        Center(<br>          child: GestureDetector(<br>            onTap: () {<br>              _showPicker(context);<br>            },<br>            child: CircleAvatar(<br>              radius: 55,<br>              backgroundColor: Color(0xffFDCF09),<br>              child: _image != null<br>                  ? ClipRRect(<br>                      borderRadius: BorderRadius.circular(50),<br>                      child: Image.file(<br>                        _image,<br>                        width: 100,<br>                        height: 100,<br>                        fit: BoxFit.fitHeight,<br>                      ),<br>                    )<br>                  : Container(<br>                      decoration: BoxDecoration(<br>                          color: Colors.grey[200],<br>                          borderRadius: BorderRadius.circular(50)),<br>                      width: 100,<br>                      height: 100,<br>                      child: Icon(<br>                        Icons.camera_alt,<br>                        color: Colors.grey[800],<br>                      ),<br>                    ),<br>            ),<br>          ),<br>        )<br>      ],<br>    ),<br>  );<br>}</pre><p>All done, Run the app and you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*Rg2lW_xfl80f_uIv.gif" /></figure><p>…</p><p><em>Originally published at </em><a href="http://fabcoding.com/adding-an-image-picker-in-a-flutter-app-pick-images-using-camera-and-gallery-photos/"><em>Fabcoding</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f016365d856" width="1" height="1" alt=""><hr><p><a href="https://medium.com/fabcoding/adding-an-image-picker-in-a-flutter-app-pick-images-using-camera-and-gallery-photos-7f016365d856">Adding an Image Picker in a Flutter App — Pick images using Camera and Gallery / Photos</a> was originally published in <a href="https://medium.com/fabcoding">fabcoding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>