<?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 mitrallex on Medium]]></title>
        <description><![CDATA[Stories by mitrallex on Medium]]></description>
        <link>https://medium.com/@mitrallex?source=rss-a810ec5d1ae4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QHbzyaCtOKp--5SS.jpeg</url>
            <title>Stories by mitrallex on Medium</title>
            <link>https://medium.com/@mitrallex?source=rss-a810ec5d1ae4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:03:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mitrallex/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[Just In Case. Fetch mode for PDO connection in Laravel]]></title>
            <link>https://codeburst.io/just-in-case-fetch-mode-for-pdo-connection-in-laravel-328fdbac6449?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/328fdbac6449</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 21:49:19 GMT</pubDate>
            <atom:updated>2021-04-08T21:50:39.233Z</atom:updated>
            <content:encoded><![CDATA[<h3>Just In Case. Fetch mode customization for PDO connection in Laravel Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lWTWetseb5KzqObQUQcBMw.png" /></figure><h3>About Just In Case</h3><p>While studying the Laravel framework, I was faced with some not-so-obvious problems (for me). One day, when I realized that it might be helpful for other people to know about it, I decided to write down all the issues that seem interesting to me. To this end, I will write series of articles with the name “Just In Case”. Information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Please note that most information about the Laravel framework can be found in the official documentation. This article offers a little more details in some cases.</em></strong></p><h3>Introduction</h3><p>In some cases we need to work with the results returned from the <a href="https://laravel.com/docs/8.x/queries">Query Builder </a>as a <a href="https://laravel.com/docs/8.x/collections">Collection</a> of arrays instead of Std Objects (<a href="https://www.php.net/manual/en/reserved.classes.php">Standard Defined Classes</a>) which is the defailt behaviour.</p><p>By the way, the results of <a href="https://laravel.com/docs/8.x/eloquent">Eloquent</a> queries are always returned as <a href="https://laravel.com/docs/8.x/collections">Collection</a> instances.</p><h3>Act</h3><p>Previously (in Laravel 5.3 and below) we <a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2Flaravel%2Fframework%2Fissues%2F17557">could set fetch mode for PDO connection from the configuration file or to do something like this</a>:</p><pre>DB::connection()-&gt;setFetchMode(\PDO::FETCH_ASSOC);</pre><p>But if you tried to do that for newer version of Laravel you will get an error :</p><pre>Call to undefined method Illuminate\Database\MySqlConnection::setFetchMode()</pre><p>In <em>vendor/laravel/framework/src/Illuminate/Database/Connection.php</em> we have a protected property:</p><pre><em>/**<br> * The default fetch mode of the connection.<br> *<br> * </em><strong><em>@var </em></strong><em>int<br> */<br>protected </em>$fetchMode = PDO::FETCH_OBJ;<br></pre><p>So as you can see by default we fetch records as objects and we can’t change this value outside the Connection class.</p><p>Actually we can do that but throught the <strong>StatementPrepared</strong> event (Illuminate\Database\Events\StatementPrepared). This evemt fires in the Connection class during configuration of prepared statement:</p><pre><em>/**<br> * Configure the PDO prepared statement.<br> *<br> * </em><strong><em>@param  </em></strong><em>\PDOStatement  $statement<br> * </em><strong><em>@return </em></strong><em>\PDOStatement<br> */<br>protected function </em>prepared(PDOStatement $statement)<br>{<br>    $statement-&gt;setFetchMode($this-&gt;fetchMode);<br><br>    $this-&gt;event(<em>new </em>StatementPrepared(<br>        $this, $statement<br>    ));<br><br>    <em>return </em>$statement;<br>}</pre><p>So, to change fetch mode of the connection we need to listen this event in some <a href="https://laravel.com/docs/8.x/providers">service provider</a>: you can use AppServiceProvider or EventServiceProvider or any other one. Add the following code in the <strong><em>boot</em></strong> method of an appropriate service provider (do not forget to import StatementPrepared class):</p><pre><em>public function </em>boot()<br>{<br>    Event::listen(StatementPrepared::<em>class</em>, <em>function</em>($event) {<br>        <em>/** </em><strong><em>@var </em></strong><em>StatementPrepared $event */<br>        </em>$event-&gt;statement-&gt;setFetchMode(\PDO::FETCH_ASSOC);<br>    });<br>}</pre><p>That’s all, now if we tried to execute some request like:</p><pre>DB::table(&#39;tasks&#39;)-&gt;get()</pre><p>As a result we will get the Collection of arrays instead of Collection of Std Objects. To ensure that you can just iterate through the result and check if each item is an array, for example:</p><pre><em>/** </em><strong><em>@var </em></strong><em>Tasks $task */<br>foreach </em>($tasks <em>as </em>$task) {<br>    $isArray = <em>is_array</em>($task);<br>}</pre><h3>Just In Case</h3><p>Do not forget to register you service provider in <strong><em>config/app.php</em></strong> in <strong>providers</strong> section. For exampler let’s register EventServiceProvider:</p><pre><em>/*<br>|--------------------------------------------------------------------------<br>| Autoloaded Service Providers<br>|--------------------------------------------------------------------------<br>|<br>| The service providers listed here will be automatically loaded on the<br>| request to your application. Feel free to add your own services to<br>| this array to grant expanded functionality to your applications.<br>|<br>*/<br><br></em>&#39;providers&#39; =&gt; [<br>    <em>/*<br>     * Laravel Framework Service Providers...<br>     */<br>    </em>Illuminate\Auth\AuthServiceProvider::<em>class</em>,<br> ...<em><br>    /*<br>     * Application Service Providers...<br>     */<br>    </em>App\Providers\AppServiceProvider::<em>class</em>,<br>    App\Providers\AuthServiceProvider::<em>class</em>,<br>    <em>// App\Providers\BroadcastServiceProvider::class,<br>    </em>App\Providers\EventServiceProvider::<em>class</em>,<br>],</pre><h3>Conclusion</h3><p>Laravel no longer includes the ability to customize the PDO “fetch mode” from your configuration files. Instead, PDO::FETCH_OBJ is always used. If you would still like to customize the fetch mode for your application you may listen for the new Illuminate\Database\Events\StatementPrepared event.</p><p>There is nothing new about the customization fetch mode of the PDO connection, but I faced with such a problem during my job and this knowledge would really save my time.</p><ul><li><a href="https://laravel.com/docs/5.4/upgrade">Upgrade Guide</a></li><li><a href="https://github.com/laravel/framework/issues/17557">[5.4] DB::setFetchMode(PDO::FETCH_ASSOC) in Laravel 5.4 · Issue #17557 · laravel/framework</a></li></ul><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it in the comments. Thank you for the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=328fdbac6449" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-fetch-mode-for-pdo-connection-in-laravel-328fdbac6449">Just In Case. Fetch mode for PDO connection in Laravel</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just In Case. Laravel environment variables in JS]]></title>
            <link>https://codeburst.io/just-in-case-laravel-environment-variables-in-js-779bc15a5e3f?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/779bc15a5e3f</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 21:02:13 GMT</pubDate>
            <atom:updated>2021-02-18T14:47:03.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lWTWetseb5KzqObQUQcBMw.png" /></figure><h3>About Just In Case</h3><p>While studying the Laravel framework, I was faced with some not-so-obvious problems (for me). One day, when I realized that it might be helpful for other people to know about it, I decided to write down all the issues that seem interesting to me. To this end, I will write series of articles with the name “Just In Case”. Information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Please note that most information about the Laravel framework can be found in the official documentation. This article offers a little more details in some cases.</em></strong></p><h3>Introduction</h3><p>Once upon a time, I needed to use a Bearer Authorization token in every AJAX request. You can achieve this by adding an appropriate header to each request, but to my mind, it is not very convenient — just imagine how many changes we would need to do if we will decided to change the authorization method (just to clarify - there will be a lot of changes, we will need to update headers for each AJAX request in the project).</p><h3>Act</h3><p>As a good solution for handling that we can define an Authorization header for each request only in one place.</p><p>In the Laravel framework, this place will be in the <strong><em>resources/js/bootstrap.js</em></strong> file. If you open this file for the first time, you can see the next lines:</p><pre><em>/**<br> * We&#39;ll load the axios HTTP library which allows us to easily issue requests<br> * to our Laravel back-end. This library automatically handles sending the<br> * CSRF token as a header based on the value of the &quot;XSRF&quot; token cookie.<br> */</em></pre><pre>window.axios = require(&#39;axios&#39;);</pre><pre>window.axios.defaults.headers.common[&#39;X-Requested-With&#39;] = &#39;XMLHttpRequest&#39;;</pre><p>In this very place we can add any common header that we need (just like <strong>X-Requested-With</strong> header). So, let’s do that and appropriate headers add here for the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization">Authorization</a> Bearer token and for the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept">accepted content-type</a> (for example):</p><pre>window.axios.defaults.headers.common[&#39;Authorization&#39;] = &#39;Bearer 9ccc75r5-3ed2-4995-8sb0-f8e77eb28a6c&#39;;<br>window.axios.defaults.headers.common[&#39;Accept&#39;] = &#39;application/json&#39;;</pre><p>But… it is so weird and not secure to keep the token in this file. So, yep, we could get this token from the environment variable. If you use <strong>laravel-mixer</strong> for your project, you can achieve it easily.</p><p>First of all you can add to your .env file a new variable, <em>API_TOKEN </em>for example:</p><pre><em>API_TOKEN=</em>9ccc75r5-3ed2-4995-8sb0-f8e77eb28a6c</pre><p>We can always use this variable in our project on the backend. But if you want to use it on the frontend — just add something like that in this very file:</p><pre><em>MIX_API_TOKEN</em>=&quot;${API_TOKEN}&quot;</pre><p>And now you can use this variable in you JS files like <strong>process.env.MIX_API_TOKEN</strong>. So we need to change an appropriate header in the <strong><em>bootstrap.js</em></strong> file:</p><pre>window.axios.defaults.headers.common[&#39;Authorization&#39;] = &#39;Bearer &#39; + process.env.MIX_API_TOKEN;</pre><p>That’s it.</p><h3>Just In Case</h3><p>If you do all the steps, but it is still not working and process.env.MIX_API_TOKEN<strong> </strong>is undefined - check your <strong><em>npm watch process</em></strong>: if it is running <strong><em>you need to rerun it</em></strong>.</p><h3>Conclusion</h3><p>It is really easy to understand and to use out of the box with the Laravel-mix. And of course the information about it you can always find in the official documentation:</p><p><a href="https://laravel.com/docs/8.x/mix#environment-variables">Compiling Assets (Mix)</a></p><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it in the comments. Thank you for the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779bc15a5e3f" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-laravel-environment-variables-in-js-779bc15a5e3f">Just In Case. Laravel environment variables in JS</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just In Case. Laravel, create custom pagination views (example with bulma)]]></title>
            <link>https://codeburst.io/just-in-case-laravel-create-custom-pagination-views-example-with-bulma-1f0bcfea1e94?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0bcfea1e94</guid>
            <category><![CDATA[php-developers]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Tue, 01 Jan 2019 07:41:35 GMT</pubDate>
            <atom:updated>2021-02-25T19:45:38.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s2y62-F6XprUL8Z_itzRA.png" /></figure><h3>About Just In Case</h3><p>While studying Laravel framework I faced with some not an obvious for me problems. And one day, when I realized that it might be helpful not only for me but for the other people to know about it, I decided to write down all the issues, that seems interesting for me.</p><p>For this purpose I will write series of articles with name “Just In Case”. So, information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Most information about Laravel framework you always can get from the official documentation. But here you can get little more details in some cases.</em></strong></p><h3>Introduction</h3><p>In this article we will create custom bulma pagination view.</p><h3>Act</h3><p>By default laravel use bootstrap pagination, but we can change that. First of all we need is execute this artisan command:</p><pre>php artisan vendor:publish --tag=laravel-pagination</pre><p>And now just replace content of the <strong><em>resources/views/vendor/pagination/default.blade.php</em></strong> with this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77b9bd6113bfc35f84a91b212dd460d/href">https://medium.com/media/f77b9bd6113bfc35f84a91b212dd460d/href</a></iframe><p>That’s all!</p><h3>Just In Case</h3><p>But there is exists another method: you can just save this gist in <strong><em>resources/views/vendor/pagination/bulma.blade.php</em></strong>. And then in your view you will use:</p><pre>{{ $data-&gt;links(&#39;vendor.pagination.bulma&#39;) }}</pre><p>Personally I prefer the second method. But which one you will use is your own choice.</p><h3>Conclusion</h3><p>In this article you found out how to create bulma pagination view, but actually you can create your own view with custom styles using this methods:</p><p><a href="https://laravel.com/docs/5.7/pagination#paginator-instance-methods">Database: Pagination - Laravel - The PHP Framework For Web Artisans</a></p><p>And, of course, first of all just read documentation:</p><p><a href="https://laravel.com/docs/5.7/pagination#customizing-the-pagination-view">Database: Pagination - Laravel - The PHP Framework For Web Artisans</a></p><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0bcfea1e94" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-laravel-create-custom-pagination-views-example-with-bulma-1f0bcfea1e94">Just In Case. Laravel, create custom pagination views (example with bulma)</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just In Case. Laravel, create foreign key in migration]]></title>
            <link>https://codeburst.io/just-in-case-laravel-create-foreign-key-in-migration-9d561cc878a8?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d561cc878a8</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php-development]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Wed, 22 Aug 2018 13:08:43 GMT</pubDate>
            <atom:updated>2021-02-17T21:21:09.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s2y62-F6XprUL8Z_itzRA.png" /></figure><h3>About Just In Case</h3><p>While studying Laravel framework I faced with some not an obvious for me problems. And one day, when I realized that it might be helpful not only for me but for the other people to know about it, I decided to write down all the issues, that seems interesting for me.</p><p>For this purpose I will write series of articles with name “Just In Case”. So, information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Most information about Laravel framework you always can get from the official documentation. But here you can get little more details in some cases.</em></strong></p><h3>Introduction</h3><p>In this article we will create foreign key constraint in migration in Laravel 5.6.</p><h3>Act</h3><p>Once I wanted to create <em>messages</em> table, and the first step that I made was creating migration for this table:</p><pre>php artisan make:migration create_messages_table --create=messages</pre><p>So that is what we get:</p><pre>Schema::<em>create</em>(<strong>&#39;messages&#39;</strong>, <strong>function </strong>(Blueprint $table) {<br>    $table-&gt;increments(<strong>&#39;id&#39;</strong>);<br>    $table-&gt;string(<strong>&#39;email&#39;</strong>);<br>    $table-&gt;text(<strong>&#39;text&#39;</strong>)-&gt;nullable();<br>    $table-&gt;integer(<strong>&#39;type_id&#39;</strong>);<br>    $table-&gt;integer(<strong>&#39;service_id&#39;</strong>)-&gt;nullable();<br>    $table-&gt;boolean(<strong>&#39;status&#39;</strong>)-&gt;default(<strong>false</strong>);<br>    $table-&gt;timestamps();<br>});</pre><p>As you can see in this schema we have <strong><em>type_id</em></strong> and <strong><em>service_id</em></strong> fields. Obviously that it will be foreign keys. So let’s add foreign key constraints to this schema (<a href="https://laravel.com/docs/5.6/migrations#foreign-key-constraints">Laravel documentation</a>):</p><pre>Schema::<em>create</em>(<strong>&#39;messages&#39;</strong>, <strong>function </strong>(Blueprint $table) {<br>    $table-&gt;increments(<strong>&#39;id&#39;</strong>);<br>    $table-&gt;string(<strong>&#39;email&#39;</strong>);<br>    $table-&gt;text(<strong>&#39;text&#39;</strong>)-&gt;nullable();<br>    $table-&gt;integer(<strong>&#39;type_id&#39;</strong>)-&gt;unsigned();<br>    $table-&gt;integer(<strong>&#39;service_id&#39;</strong>)-&gt;unsigned()-&gt;nullable();<br>    $table-&gt;boolean(<strong>&#39;status&#39;</strong>)-&gt;default(<strong>false</strong>);<br>    $table-&gt;timestamps();<br><br>    $table-&gt;foreign(<strong>&#39;type_id&#39;</strong>)<br>            -&gt;references(<strong>&#39;id&#39;</strong>)<br>            -&gt;on(<strong>&#39;message_types&#39;</strong>)<br>            -&gt;onDelete(<strong>&#39;cascade&#39;</strong>);<br><br><br>    $table-&gt;foreign(<strong>&#39;service_id&#39;</strong>)<br>            -&gt;references(<strong>&#39;id&#39;</strong>)<br>            -&gt;on(<strong>&#39;services&#39;</strong>)<br>            -&gt;onDelete(<strong>&#39;cascade&#39;</strong>);<br>});</pre><p>All right, now let’s create <em>message_types</em> table:</p><pre>php artisan make:migration create_message_types_table --create=message_types</pre><p>And <em>services</em> table:</p><pre>php artisan make:migration create_services_table --create=services</pre><p>There are no matters how schemas of these tables look like in this case. So now we have three migrations for tables messages, message_types and services. It’s great!</p><p>Now we can run our migrations:</p><pre>php artisan migrate</pre><h3>Just In Case</h3><p>But wait.. it’s not working! And here is the error:</p><pre>errno: 150 &quot;Foreign key constraint is incorrectly formed&quot;</pre><p>And the main reason is that <strong><em>Laravel created messages table and then tried to create foreign key constraint to table message_types that don’t exists yet</em></strong>.</p><p>If you look at your any migration file name, you can see that it starts from the date and time. For example <strong><em>create_users_table</em></strong>:</p><pre>2014_10_12_000000_create_users_table</pre><p><strong><em>And Laravel migrations run earlier files at first.</em></strong> So in our case we just need to edit the file name of our <em>create_messages_table</em> migration as if we created this migration after <em>create_message_types_table</em> and <em>create_services_table</em> migrations.</p><h3>Conclusion</h3><p><strong><em>The order of migration file is very important</em></strong> so my advice to you is <strong><em>always try to prepare you tables and relations between them on the paper</em></strong> at first. And only then generate migrations that you need in the right order. I think it will be nice to make it habit.</p><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d561cc878a8" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-laravel-create-foreign-key-in-migration-9d561cc878a8">Just In Case. Laravel, create foreign key in migration</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just In Case. Laravel, handling active menu item]]></title>
            <link>https://codeburst.io/just-in-case-laravel-handling-active-menu-item-932afe59cf9b?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/932afe59cf9b</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 18:27:06 GMT</pubDate>
            <atom:updated>2021-02-17T21:42:45.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s2y62-F6XprUL8Z_itzRA.png" /></figure><h3>About Just In Case</h3><p>While studying Laravel framework I faced with some not an obvious for me problems. And one day, when I realized that it might be helpful not only for me but for the other people to know about it, I decided to write down all the issues, that seems interesting for me.</p><p>For this purpose I will write series of articles with name “Just In Case”. So, information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Most information about Laravel framework you always can get from the official documentation. But here you can get little more details in some cases.</em></strong></p><h3>Introduction</h3><p>In this article we will create custom helper function for handling active menu item in Laravel 5.6.</p><h3>Act</h3><p>Of course you can do that any way you want and one of the method is use this line in your blade file:</p><pre><strong>@if(</strong>Request::<em>path</em>() === <strong>&#39;products&#39;)<br>    ...<br>@endif</strong></pre><p>But what if here will be 10 menu items or even more? It will be too messy, I think. So the best practice for me for handling active menu item is create function in one place and call it from any place of your project.</p><p>So just create <strong><em>Helpers</em></strong> directory in your <strong><em>App</em></strong> folder and here create the <strong><em>CustomHelpers.php</em></strong> file with the following content:</p><pre><strong>&lt;?php<br><br></strong><em>/**<br> *<br> * Set active css class if the specific URI is current URI<br> *<br> * </em><strong><em>@param </em></strong><em>string $path       A specific URI<br> * </em><strong><em>@param </em></strong><em>string $class_name Css class name, optional<br> * </em><strong><em>@return </em></strong><em>string            Css class name if it&#39;s current URI,<br> *                           otherwise - empty string<br> */<br></em><strong>function </strong>setActive(string $path, string $class_name = <strong>&quot;is-active&quot;</strong>)<br>{<br>    <strong>return </strong>Request::<em>path</em>() === $path ? $class_name : <strong>&quot;&quot;</strong>;<br>}</pre><p>This function get one required and one optional parameters. In my project I use <a href="https://bulma.io/">Bulma css framework</a>, so active class will be <em>‘is-active’ </em>. Nevertheless you always can define here your class name, or just give the specific class name from the Blade template file. For example for the Bootstrap active item will be:</p><pre>&lt;a class=&quot;{{ setActive(&#39;products&#39;, &#39;active&#39;) }}&quot;&gt;Products&lt;/a&gt;</pre><p>Now let’s say our Laravel application that we can use functions from the <strong><em>CustomHelpers.php</em></strong> file. Just add in the <strong><em>composer.json</em></strong>:</p><pre><strong>&quot;autoload&quot;</strong>: {<br>    <strong>&quot;classmap&quot;</strong>: [<br>        <strong>&quot;database/seeds&quot;</strong>,<br>        <strong>&quot;database/factories&quot;<br>    </strong>],<br>    <strong>&quot;psr-4&quot;</strong>: {<br>        <strong>&quot;App\\&quot;</strong>: <strong>&quot;app/&quot;<br>    </strong>},<br>    <strong>&quot;files&quot;</strong>: [                         // ADD<br>      <strong>&quot;app/Helpers/CustomHelpers.php&quot;  // THIS<br>    </strong>]                                  // LINES<br>},</pre><h3>Just In Case</h3><p>Don’t forget after editing the <strong><em>composer.json</em></strong> run this command:</p><pre>composer dump-autoload</pre><p>For more information read <a href="https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload-">Composer documentation</a>.</p><h3>Update. Sub menu items</h3><p>If you want to handle submenu items, you can try to use this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d78bc60434c75d4e57b03e877aecedf/href">https://medium.com/media/7d78bc60434c75d4e57b03e877aecedf/href</a></iframe><p><em>Thanks to </em><a href="https://medium.com/u/fc2854755c28"><em>Yassine Belkaid</em></a><em> for the help.</em></p><h3>Conclusion</h3><p>With this method you’ll be able to create any helper function for your needs in a specific project, but this the <strong><em>setActive()</em></strong> function will be helpful in any of your Laravel project.</p><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=932afe59cf9b" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-laravel-handling-active-menu-item-932afe59cf9b">Just In Case. Laravel, handling active menu item</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just In Case. Laravel, create custom Blade directive]]></title>
            <link>https://codeburst.io/just-in-case-laravel-create-custom-blade-directive-b60a7160949d?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b60a7160949d</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[laravel-tutorials]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 08:44:29 GMT</pubDate>
            <atom:updated>2021-02-17T21:43:28.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s2y62-F6XprUL8Z_itzRA.png" /></figure><h3>About Just In Case</h3><p>While studying Laravel framework I faced with some not an obvious for me problems. And one day, when I realized that it might be helpful not only for me but for the other people to know about it, I decided to write down all the issues, that seems interesting for me.</p><p>For this purpose I will write series of articles with name “Just In Case”. So, information from these articles might not be very important but, you know, it’s <em>just in case</em> information.</p><p><strong><em>Most information about Laravel framework you always can get from the official documentation. But here you can get little more details in some cases.</em></strong></p><h3>Introduction</h3><p>This is the first article from this series and in this article let’s talk about creating custom Blade directives in Laravel 5.6.</p><h3>Act</h3><p>About Blade templates you can read from the <a href="https://laravel.com/docs/5.6/blade">Laravel documentation</a>. Here you can also find information about <a href="https://laravel.com/docs/5.6/blade#extending-blade">custom Blade directives</a>.</p><p>In the documentation new Blade directive creates in <strong><em>AppServiceProvider.php</em></strong>. But in my own opinion it will be much better to create dedicated provider. So let’s create new service provider:</p><pre>php artisan make:provider BladeServiceProvider</pre><p>After that don’t forget to add your new service provider in the <strong><em>/config/app.php</em></strong> file in the <em>providers</em> array:</p><pre>App\Providers\BladeServiceProvider::<strong>class</strong></pre><p>Now open our <strong><em>BladeServiceProvider.php </em></strong>and use Blade facade on the top of the file:</p><pre><strong>use </strong>Illuminate\Support\Facades\Blade;</pre><p>After that there is the last step, in the boot method create your custom directive, for example:</p><pre>Blade::<em>directive</em>(<strong>&#39;message_type&#39;</strong>, <strong>function</strong>($type_id) {<br>    <strong>return &quot;&lt;input id=\&quot;message_type\&quot; type=\&quot;hidden\&quot; name=\&quot;type_id\&quot; value=\&quot;</strong>{$type_id}<strong>\&quot;&gt;&quot;</strong>;<br>});</pre><p>This directive will create hidden input field with a given value. So now you can use it in any Blade file:</p><pre>@message_type(1)</pre><p>Well done!</p><h3>Just In Case</h3><p>When I created my own directive in the first time, it didn’t work as I expected. The main point is that Laravel caches all views and you just need to clear this cache with the next Artisan command:</p><pre>php artisan view:clear</pre><p>Now refresh your page and enjoy the result.</p><h3>Conclusion</h3><p>But the main point of this article is that many issues can be resolved quickly only if you will carefully read the documentation (it’s really works for me):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*lfSGltd1mQ_YvNuINV8WzA.png" /></figure><p><strong><em>P.S.</em></strong> If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b60a7160949d" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/just-in-case-laravel-create-custom-blade-directive-b60a7160949d">Just In Case. Laravel, create custom Blade directive</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple integration Google reCAPTCHA v2 with Laravel in details]]></title>
            <link>https://codeburst.io/simple-integration-google-recaptcha-v2-with-laravel-in-details-2db49d1d8e60?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db49d1d8e60</guid>
            <category><![CDATA[recaptcha]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 13:33:54 GMT</pubDate>
            <atom:updated>2021-02-25T20:02:26.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxYHlUNcZ-U2l4fqFqdRiw.png" /></figure><h3>Introduction</h3><p>One week ago I started to migrate one of my project to the Laravel framework. And Google reCAPTCHA v2 validation was the first problem I faced. After solving this problem I decided for myself how I would do that for the next time in all my projects (if it will be necessary).</p><p>For this purpose let’s create a simple small project that just will allow us to send a feedback. In this project we will use <a href="https://getbootstrap.com/">Bootstrap 4 css framework</a>, <a href="https://vuejs.org/">Vue.js</a> and <a href="https://www.npmjs.com/package/axios">axios library</a> for AJAX requests. So, in the end we must have feedback form that send AJAX request to the server where we validate data and if all right create new record in the database. So simple, let’s do it.</p><h3>Preparation</h3><p>First of all, we need such parameters for <a href="https://developers.google.com/recaptcha/">Google reCAPTCHA</a> as site key and secret key. In our case we will use <a href="https://developers.google.com/recaptcha/docs/faq">testing parameters</a>, so just add this two lines to your .env file:</p><pre>GOOGLE_RECAPTCHA_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI<br>GOOGLE_RECAPTCHA_SECRET=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe</pre><p><a href="https://developers.google.com/recaptcha/docs/verify">Read more about how to verify user’s response from the application’s backend</a>.</p><p>For verifying user’s response we need to send POST request to this url: <a href="https://www.google.com/recaptcha/api/siteverify">https://www.google.com/recaptcha/api/siteverify</a>. For that we will use Client class from <a href="https://github.com/guzzle/guzzle">guzzlehttp package</a>.</p><p>So just run this command in project folder for adding this package to your composer.json file:</p><pre>composer require guzzlehttp/guzzle</pre><p>The next step is to create Feedback model, Feedback controller and migration for feedback model:</p><pre>php artisan make:model Feedback -mc</pre><p>Create Feedback request class:</p><pre>php artisan make:request FeedbackRequest</pre><p>And the main thing is creating rule for reCAPTCHA validation:</p><pre>php artisan make:rule ValidRecaptcha</pre><blockquote><strong>WARNING!</strong></blockquote><blockquote>If you use MariaDB there is can be a problem to work with DBMS via artisan command. In this case all that you need is using this in <strong><em>AppServiceProvider</em></strong>:</blockquote><pre><strong>use </strong>Illuminate\Support\Facades\Schema;</pre><pre><strong>public function </strong>boot()<br>{<br>    Schema::<em>defaultStringLength</em>(191);<br>}</pre><h3>Routes</h3><p>On the main page we will see feedback form. And for the comfort let’s create page with all out feedback messages (here we can delete a specific feedback, if we want to).</p><pre>Route::<em>get</em>(<strong>&#39;/&#39;</strong>, <strong>&#39;FeedbackController@create&#39;</strong>);<br>Route::<em>get</em>(<strong>&#39;/feedback&#39;</strong>, <strong>&#39;FeedbackController@index&#39;</strong>);<br>Route::<em>post</em>(<strong>&#39;/feedback/create&#39;</strong>, <strong>&#39;FeedbackController@store&#39;</strong>);<br>Route::<em>get</em>(<strong>&#39;/feedback/delete/{id}&#39;</strong>, <strong>&#39;FeedbackController@destroy&#39;</strong>);</pre><h3>Frontend</h3><h4>Views</h4><p>I think that we can skip the main layout file <strong><em>app.blade.php</em></strong> and look only at pages: <strong><em>create.blade.php</em></strong> and <strong><em>index.blade.php</em></strong>.</p><p><strong>index.blade.php</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44515d6fd686021eff22edf0615a284a/href">https://medium.com/media/44515d6fd686021eff22edf0615a284a/href</a></iframe><p>As you can see there are no interesting things in here.</p><p><strong>create.blade.php</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0002cfa9421cf4c3b8a8809af9c64627/href">https://medium.com/media/0002cfa9421cf4c3b8a8809af9c64627/href</a></iframe><p>The main thing here for put article is this line:</p><pre>&lt;<strong>div class=&quot;g-recaptcha&quot; id=&quot;feedback-recaptcha&quot; data-sitekey=&quot;</strong>{{ env(<strong>&#39;GOOGLE_RECAPTCHA_KEY&#39;</strong>)  }}<strong>&quot;</strong>&gt;&lt;/<strong>div</strong>&gt;</pre><p>But don’t forget in main layout file add this line:</p><pre><strong>&lt;script src=&quot;https://www.google.com/recaptcha/api.js&quot; async defer&gt;&lt;/script&gt;</strong></pre><h4>Styles</h4><p><strong>/resources/assets/sass/app.scss</strong></p><pre><em>// Fonts<br></em>@import url(https://medium.com/&#39;https://fonts.googleapis.com/css?family=Nunito&#39;);<br><br><em>// Variables<br></em>@import &#39;variables&#39;;<br><br><em>// Bootstrap<br></em>@import &#39;~bootstrap/scss/bootstrap&#39;;<br><br>.navbar {<br>  background-color: #e3f2fd;<br>}<br><br>.container {<br>  margin-top: 20px;<br>}<br><br>.btn-feedback-block {<br>  margin-top: 15px;<br>}</pre><h4>JavaScript</h4><p><strong>/resources/assets/js/app.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f81d83ad039b1cf5f2224ae9c07d16a/href">https://medium.com/media/3f81d83ad039b1cf5f2224ae9c07d16a/href</a></iframe><p>In this file you can see, that here we use <a href="https://sweetalert2.github.io/">SweetAlert2 library</a>.</p><p>In this line we get value of our reCAPTCHA input and add this value to our FormData object:</p><pre>form_data.append(<strong>&#39;g-recaptcha-response&#39;</strong>, <strong>$</strong>(<strong>&quot;#g-recaptcha-response&quot;</strong>).val());</pre><h3>Backend</h3><h4>Database</h4><p>Our table structure in create_feedback_table.php:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abae0bd8e274ae878f531b251eaea46b/href">https://medium.com/media/abae0bd8e274ae878f531b251eaea46b/href</a></iframe><h4>Model</h4><p>Model is empty:</p><pre><strong>class </strong>Feedback <strong>extends </strong>Model<br>{<br>    <em>//<br></em>}</pre><h4>Controller</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b76dcd4f3af48d5b934a9f82ff37667/href">https://medium.com/media/9b76dcd4f3af48d5b934a9f82ff37667/href</a></iframe><p>Here we see that we get FeedbackRequest as a parameter in the <em>store()</em> method. So after that our request validates in the <strong><em>FeedbackRequest.php</em></strong> file.</p><h4>Request</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b98a73cdcd31a19513644f54cc9b2e13/href">https://medium.com/media/b98a73cdcd31a19513644f54cc9b2e13/href</a></iframe><p>Change return value of the authorize() method to true:</p><pre><strong>public function </strong>authorize()<br>{<br>    <strong>return true</strong>;<br>}</pre><p>Use rule ValidRecaptcha in this file:</p><pre><strong>use </strong>App\Rules\ValidRecaptcha;</pre><p>Create validation rules:</p><pre><strong>public function </strong>rules()<br>{<br>    <strong>return </strong>[<br>        <strong>&#39;name&#39; </strong>=&gt; <strong>&#39;required&#39;</strong>,<br>        <strong>&#39;email&#39; </strong>=&gt; <strong>&#39;required|email&#39;</strong>,<br>        <strong>&#39;message&#39; </strong>=&gt; <strong>&#39;required&#39;</strong>,<br>        <strong>&#39;g-recaptcha-response&#39; </strong>=&gt; [<strong>&#39;required&#39;</strong>, <strong>new </strong>ValidRecaptcha]<br>    ];<br>}</pre><p>Set message for our g-recaptcha-response required field:</p><pre><strong>public function </strong>messages()<br>{<br>    <strong>return </strong>[<br>        <strong>&#39;g-recaptcha-response.required&#39; </strong>=&gt; <strong>&#39;Please ensure that you are a human!&#39;<br>    </strong>];<br>}</pre><p>Now let’s create new rule for reCAPTCHA validation.</p><h4>Rule</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/161bcd22326742d0aa8a69fc0a274e45/href">https://medium.com/media/161bcd22326742d0aa8a69fc0a274e45/href</a></iframe><p>Use Client class from GuzzleHttp:</p><pre><strong>use </strong>GuzzleHttp\Client;</pre><p>Create new object with <em>base_uri</em>:</p><pre>$client = <strong>new </strong>Client([<br>    <strong>&#39;base_uri&#39; </strong>=&gt; <strong>&#39;https://google.com/recaptcha/api/&#39;<br></strong>]);</pre><p>Send post request with secret from our .env file and with the value from out g-recaptcha-response field:</p><pre>$response = $client-&gt;<strong>post</strong>(<strong>&#39;siteverify&#39;</strong>, [<br>    <strong>&#39;query&#39; </strong>=&gt; [<br>        <strong>&#39;secret&#39; </strong>=&gt; env(<strong>&#39;GOOGLE_RECAPTCHA_SECRET&#39;</strong>),<br>        <strong>&#39;response&#39; </strong>=&gt; $value<br>    ]<br>]);</pre><p>Get response body and return result:</p><pre><strong>return </strong><em>json_decode</em>($response-&gt;getBody())-&gt;<strong>success</strong>;</pre><p>If the <em>passes() </em>method return false we will get the next message:</p><pre><strong>public function </strong>message()<br>{<br>    <strong>return &#39;ReCaptcha verification failed.&#39;</strong>;<br>}</pre><h3>Result</h3><h4>Feeback form</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sI18ssiV1DT8WvW9YwltFg.png" /><figcaption>Feedback form</figcaption></figure><h4>Feedback messages list</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btMlDuDKBSL0DMHOANKlWQ.png" /><figcaption>Feedback messages list</figcaption></figure><h4>Data is invalid</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAPF4kdN_hm0xihkxOfnVA.png" /><figcaption>Data is invalid 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoEPrBTQx9P9-i-Bf6WH1w.png" /><figcaption>Data is invalid 2</figcaption></figure><h4>Feedback successfully send</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wamrekLF5ukCUMtteNMbqQ.png" /><figcaption>Feedback successfully send</figcaption></figure><h3>Conclusion</h3><p>The main point of this article is figure out how we can validate Google reCAPTCHA in our laravel application. It’s all about server side validation and right now this solution seem the best practice for me.</p><p><strong><em>P.S.</em></strong> The source code available on <a href="https://github.com/fl2top/laravel-google-recaptcha">GitHub</a>. If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db49d1d8e60" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/simple-integration-google-recaptcha-v2-with-laravel-in-details-2db49d1d8e60">Simple integration Google reCAPTCHA v2 with Laravel in details</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload and manage files with Laravel and Vue]]></title>
            <link>https://codeburst.io/upload-and-manage-files-with-laravel-and-vue-915378c8b2a4?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/915378c8b2a4</guid>
            <category><![CDATA[bulma]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 08:32:49 GMT</pubDate>
            <atom:updated>2021-02-25T20:25:55.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYYeO7ZaS9bqe0D29vF5XA.jpeg" /></figure><h3>Preview</h3><p>In this time we build simple service that allow us to upload and manage files. Here is UI for that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bb_lAybGc8y5Vigy9RFVEA.png" /><figcaption>Preview image with UI</figcaption></figure><h3>Preparing</h3><p>First of all change value of this directives in your php.ini:</p><pre>upload_max_filesize = 200m<br>post_max_size = 250m</pre><p>Some dependencies in <strong><em>packages.json</em></strong>:</p><pre>&quot;devDependencies&quot;: {<br>    &quot;axios&quot;: &quot;^0.17&quot;,<br>    &quot;bootstrap-sass&quot;: &quot;^3.3.7&quot;,<br>    &quot;cross-env&quot;: &quot;^5.1&quot;,<br>    &quot;jquery&quot;: &quot;^3.2&quot;,<br>    &quot;laravel-mix&quot;: &quot;^1.0&quot;,<br>    &quot;lodash&quot;: &quot;^4.17.4&quot;,<br>    &quot;vue&quot;: &quot;^2.5.7&quot;<br>},<br>&quot;dependencies&quot;: {<br>    &quot;bulma&quot;: &quot;^0.5.1&quot;,    <br>    &quot;font-awesome&quot;: &quot;^4.7.0&quot;<br>}</pre><p>Generating assets with laravel mix — <strong><em>webpack.mix.js</em></strong>:</p><pre>let mix = require(&#39;laravel-mix&#39;);</pre><pre>mix.options({<br>    processCssUrls: false<br>});</pre><pre>mix.js(&#39;resources/assets/js/app.js&#39;, &#39;public/js&#39;)<br>   .sass(&#39;resources/assets/sass/app.scss&#39;, &#39;public/css&#39;)<br>   .sass(&#39;resources/assets/sass/font-awesome.scss&#39;, &#39;public/css&#39;);</pre><p>Set path in <strong><em>font-awesome.scss</em></strong> and import fonts:</p><pre>// Fonts<br>$fa-font-path: &quot;../fonts/vendor/font-awesome&quot;;<br><a href="http://twitter.com/import">@import</a> &#39;~font-awesome/scss/font-awesome.scss&#39;;</pre><p>Also import bulma styles in <strong><em>app.scss</em></strong>:</p><pre>// Bulma<br><a href="http://twitter.com/import">@import</a> &quot;~bulma/bulma.sass&quot;;</pre><p>Another styles you can see on <a href="https://github.com/fl2top/laravel-file-hosting/blob/master/resources/assets/sass/app.scss">GitHub</a>.</p><blockquote><strong>WARNING!</strong></blockquote><blockquote>If you use MariaDB there is can be a problem to work with DBMS via artisan command. In this case all that you need is using this in <strong><em>AppServiceProvider</em></strong>:</blockquote><pre>use Illuminate\Support\Facades\Schema;</pre><pre>public function boot()<br>{<br>    Schema::defaultStringLength(191);<br>}</pre><p>Another important thing is creating symbolic link in public directory to <em>storage/app/public/ </em>with artisan command:</p><pre>php artisan storage:link</pre><p>Now you can create a URL to the files using the <em>asset</em> helper:</p><pre>echo asset(&#39;storage/file.txt&#39;);</pre><p>In this case we will use laravel authentication out of the box, so:</p><pre>php artisan make:auth</pre><h3>Routes</h3><p>After all our <strong><em>web.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d56a93e7976837b258a363759d01fb25/href">https://medium.com/media/d56a93e7976837b258a363759d01fb25/href</a></iframe><h3>Database</h3><p>You can create model, migration and controller in one artisan commad:</p><pre>php artisan make:model -mc</pre><p>Leave <strong><em>create_users_table</em></strong> and <strong><em>create_passwords_resets_table</em></strong> migrations unchanged. And here is table structure from <strong><em>create_files_table</em></strong> migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e789d68de86d95049719494c55d210a2/href">https://medium.com/media/e789d68de86d95049719494c55d210a2/href</a></iframe><p>Eloquent ORM model <strong><em>File.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1c077d37d47931dabcf74bdbae97d4d/href">https://medium.com/media/b1c077d37d47931dabcf74bdbae97d4d/href</a></iframe><h3>Controller</h3><p>We have two controllers - <strong><em>MainController</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d426766a5225cd07662ceffce5c1863/href">https://medium.com/media/3d426766a5225cd07662ceffce5c1863/href</a></iframe><p>and <strong><em>FileController</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5961e3e059ba951855abb8d5f4f9d9/href">https://medium.com/media/bb5961e3e059ba951855abb8d5f4f9d9/href</a></iframe><p>In this controller we contain four arrays of file extensions, that used for validation. You can expand this list.</p><p>In the constructor we define middleware for this controller.</p><p>In the <strong><em>index</em></strong> method we fetch all files with specific type and user id using <em>paginate</em> method. Then prepare response for the client and return it in json format:</p><pre>$response = [<br>    &#39;pagination&#39; =&gt; [<br>        &#39;total&#39; =&gt; $files-&gt;total(),<br>        &#39;per_page&#39; =&gt; $files-&gt;perPage(),<br>        &#39;current_page&#39; =&gt; $files-&gt;currentPage(),<br>        &#39;last_page&#39; =&gt; $files-&gt;lastPage(),<br>        &#39;from&#39; =&gt; $files-&gt;firstItem(),<br>        &#39;to&#39; =&gt; $files-&gt;lastItem()<br>    ],<br>    &#39;data&#39; =&gt; $files<br>];</pre><pre>return response()-&gt;json($response);</pre><p>In the <strong><em>store</em></strong> method we upload file and create new record for this file in the database. But first of all we prepare for validation by getting max file size and all allowed extensions:</p><pre>$max_size = (int)ini_get(&#39;upload_max_filesize&#39;) * 1000;<br>$all_ext = implode(&#39;,&#39;, $this-&gt;allExtensions());</pre><p>Now let’s validate request data: <em>name</em> must be required and unique, <em>file</em> - required , it is must be a file, this file must be with certain extensions and max file size must be not more than a certain value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711d8e7543a5609e47c6c3277fb9822f/href">https://medium.com/media/711d8e7543a5609e47c6c3277fb9822f/href</a></iframe><p>Get file and file information (extension and type):</p><pre>$file = $request-&gt;file(&#39;file&#39;);<br>$ext = $file-&gt;getClientOriginalExtension();<br>$type = $this-&gt;getType($ext);</pre><p>And now we can upload file (<a href="https://laravel.com/docs/5.5/filesystem">File Storage</a>) on the disk in the user personal directory (<strong>storage/public/{user_name}/{file_type}/{file_name}</strong>). If file is uploaded successfully — create new record in the database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7cfde466564a20bc33959985f61f0fd/href">https://medium.com/media/f7cfde466564a20bc33959985f61f0fd/href</a></iframe><p>You can change filename in the <strong><em>edit</em></strong> method. The new name should be different from the old one and it is must be unique. After validation we check file existence. If file exist, rename it and change filename in the database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a02930caeac675644aee97ef6c3cea08/href">https://medium.com/media/a02930caeac675644aee97ef6c3cea08/href</a></iframe><p>And, of course, here is the <strong><em>destroy</em></strong> method. If file exist, delete file from the disk and then delete record from the database:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d328e8d736e33f9b9317d3738ac971/href">https://medium.com/media/e4d328e8d736e33f9b9317d3738ac971/href</a></iframe><p>The other methods are very obvious, so you can view it yourself.</p><h3>Views</h3><p>In this case we have main view and views for authorization and layouts.</p><h4>Layouts</h4><p>Main layout file is <strong><em>app.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/332651ec2ee062ad9399926a81e420d7/href">https://medium.com/media/332651ec2ee062ad9399926a81e420d7/href</a></iframe><p>As you can see in this file we include some other views. It’s notification, file-form, confirm and modal view. But we include them only if user is authorized.</p><p><em>Keep in mind that you can realize all these layouts with Vue components!</em></p><p>Here are all the layouts:</p><p><strong><em>file-form.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eba6ef0256019e9a27eb701402d1bb96/href">https://medium.com/media/eba6ef0256019e9a27eb701402d1bb96/href</a></iframe><p>In this layout you can see form for file sending. Here are the key points:</p><p>Call the function <strong><em>SubmitForm</em></strong> on form submitting:</p><pre>&lt;form id=&quot;new-file-form&quot; <a href="http://twitter.com/submit">@submit</a>.prevent=&quot;submitForm&quot;&gt;</pre><p>Define v-model for filename:</p><pre>&lt;input class=&quot;input&quot; type=&quot;text&quot; name=&quot;name&quot; placeholder=&quot;File name&quot; v-model=&quot;fileName&quot; required&gt;</pre><p>Add attribute <em>ref </em>to the input field with file type: now we can access this input from Vue in a second. And another attribute is event handler <em>change. </em>When the user uploads a file we call the <strong><em>AddFile</em></strong> method:</p><pre>&lt;input class=&quot;file-input&quot; type=&quot;file&quot; ref=&quot;file&quot; name=&quot;file&quot; <a href="http://twitter.com/change">@change</a>=&quot;addFile()&quot;&gt;</pre><p>If exist attachment name, we show it and update inner HTML of the span element:</p><pre>&lt;span class=&quot;file-name&quot; v-if=&quot;attachment.name&quot; v-html=&quot;attachment.name&quot;&gt;&lt;/span&gt;</pre><p><strong><em>notification.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7207b0e5a73e676fd94eea329ff8fd5d/href">https://medium.com/media/7207b0e5a73e676fd94eea329ff8fd5d/href</a></iframe><p>In this case we use transition with name fade . <a href="https://vuejs.org/v2/guide/transitions.html#CSS-Transitions">Here is details</a>.</p><p>Show notification on success or on error: if we have any error notification has class <em>is-danger</em>, otherwise — <em>is-success</em>. So it is:</p><pre>&lt;div class=&quot;notification is-success&quot; v-cloak v-if=&quot;!anyError()&quot;&gt;</pre><p>or</p><pre>&lt;div class=&quot;notification is-danger&quot; v-cloak v-if=&quot;anyError()&quot;&gt;</pre><p>And you can close notification:</p><pre>&lt;button class=&quot;delete&quot; <a href="http://twitter.com/click">@click</a>=&quot;notification=false&quot;&gt;&lt;/button&gt;</pre><p><strong><em>modal.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bcd586131a4739982dc8384eaba7547/href">https://medium.com/media/7bcd586131a4739982dc8384eaba7547/href</a></iframe><p>Div element has class <em>is-active </em>if the property <em>modalActive </em>is true .</p><p>Show this element only with images, so let’s form a link to the specific image:</p><pre>&lt;img src=&quot;&quot;  :src=&quot;&#39;{{ asset(&#39;storage/&#39; . Auth::user()-&gt;name . &#39;_&#39; . Auth::id()) }}&#39; + &#39;/&#39; + file.type + &#39;/&#39; + file.name + &#39;.&#39; + file.extension&quot; :alt=&quot;file.name&quot;&gt;</pre><p>Close modal window by clicking to the background:</p><pre>&lt;div class=&quot;modal-background&quot; <a href="http://twitter.com/click">@click</a>=&quot;closeModal()&quot;&gt;&lt;/div&gt;</pre><p>or by clicking to the button:</p><pre>&lt;button class=&quot;modal-close is-large&quot; aria-label=&quot;close&quot; <a href="http://twitter.com/click">@click</a>=&quot;closeModal()&quot;&gt;&lt;/button&gt;</pre><p><strong><em>confirm.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871a4a91e19032598fac2da133526ed1/href">https://medium.com/media/871a4a91e19032598fac2da133526ed1/href</a></iframe><p>Show custom confirm on file deleting with transition:</p><pre>&lt;transition name=&quot;modal&quot;&gt;<br>    &lt;div class=&quot;modal-mask&quot; v-if=&quot;showConfirm&quot; v-cloak&gt;<br>    ...<br>    &lt;/div&gt;<br>&lt;/transition&gt;</pre><p>Delete file on confirm:</p><pre>&lt;button class=&quot;button&quot; <a href="http://twitter.com/click">@click</a>=&quot;deleteFile()&quot;&gt;<br>    Confirm<br>&lt;/button&gt;</pre><p>Otherwise - cancel deleting:</p><pre>&lt;button class=&quot;button&quot; <a href="http://twitter.com/click">@click</a>=&quot;cancelDeleting()&quot;&gt;<br>    Cancel<br>&lt;/button&gt;</pre><h4>Auth</h4><p>In this case we just change default views from bootstrap templates to bulma templates. All auth templates you can see on <a href="https://github.com/fl2top/laravel-file-hosting/tree/master/resources/views/auth">GitHub</a>.</p><h4>Main view</h4><p>The main view is <strong><em>main.blade.php</em></strong>, which extends <strong><em>app.blade.php</em></strong>. So, let’s take a closer look at <strong><em>main.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046152fd2d85fd94094754c4c32c31b5/href">https://medium.com/media/046152fd2d85fd94094754c4c32c31b5/href</a></iframe><p>We have four tabs: list of file type names. You can change tab by clicking. For example:</p><pre>&lt;li :class=&quot;{&#39;is-active&#39;: isActive(&#39;image&#39;)}&quot; <a href="http://twitter.com/click">@click</a>=&quot;getFiles(&#39;image&#39;)&quot;&gt;</pre><p>There are three other sections in tabs-detail section.</p><p>The first — if there are no files:</p><pre>&lt;div class=&quot;is-empty column is-4 is-offset-4&quot; v-if=&quot;pagination.total == 0&quot; v-cloak&gt;</pre><p>The second — for loading:</p><pre>&lt;div class=&quot;loading column is-4 is-offset-4&quot; v-if=&quot;loading&quot;&gt;<br>    &lt;i class=&quot;fa fa-spinner fa-pulse fa-3x fa-fw&quot;&gt;&lt;/i&gt;<br>    &lt;span class=&quot;sr-only&quot;&gt;Loading...&lt;/span&gt;<br>&lt;/div&gt;</pre><p>And the third — for all our records:</p><pre>&lt;div class=&quot;column &quot; :class=&quot;isVideo  ? &#39;is-half&#39;  : &#39;is-one-fifth&#39;&quot; v-for=&quot;file in files&quot; v-cloak&gt;</pre><p><em>And in the last section all the magic.</em></p><p>As you can see, if current tab is contain videos - class is-half, otherwise - is-one-fifth.</p><p>For each record (file) we have a card (<a href="https://bulma.io/documentation/components/card/">card component with bulma.io</a>). Card has class is-image if file type is image (for scaling card on hover - <em>see app.scss for details</em>):</p><pre>&lt;div class=&quot;card&quot; :class=&quot;file.type == &#39;image&#39; ? &#39;is-image&#39; : &#39;&#39;&quot;&gt;</pre><p><strong>In the each card you can find:</strong></p><ul><li><strong>button for file deleting:</strong></li></ul><pre>&lt;button class=&quot;delete delete-file&quot; title=&quot;Delete&quot; <a href="http://twitter.com/click">@click</a>=&quot;prepareToDelete(file)&quot;&gt;&lt;/button&gt;</pre><ul><li><strong>card image (depends on file type):</strong></li></ul><p><em>if file type is image:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede94c1175a78560c85b4cbe2cab5bba/href">https://medium.com/media/ede94c1175a78560c85b4cbe2cab5bba/href</a></iframe><p>In this case show modal with the specific image by clicking.</p><p><em>if file type is audio:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3713d55192d5942d36a25d14e8f5f361/href">https://medium.com/media/3713d55192d5942d36a25d14e8f5f361/href</a></iframe><p><em>if file type is video:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f03920607f1cd7733591af57faaef57/href">https://medium.com/media/9f03920607f1cd7733591af57faaef57/href</a></iframe><p><em>if file type is document:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca149a1ae883dea7b2c3e0a36a9d5f3b/href">https://medium.com/media/ca149a1ae883dea7b2c3e0a36a9d5f3b/href</a></iframe><ul><li><strong>card content:</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c39b773af1dc47c365c7ca1e1d2d97e3/href">https://medium.com/media/c39b773af1dc47c365c7ca1e1d2d97e3/href</a></iframe><p>You can change filename by double clicking. Example with the same functionality (edit record by double clicking with custom directive) you can find in my article <a href="https://codeburst.io/vue-components-with-a-simple-example-for-beginners-from-beginner-b0d4ff84aa62"><em>View components with a simple example</em></a>.</p><p>After tabs content there is a pagination element here, which only will display if count of the pages is more than one. If you want to see pagination in action, you can read my another article <a href="https://codeburst.io/pagination-with-ajax-request-using-laravel-and-vue-fc584b6fa1ea"><em>Pagination with ajax request using Laravel and Vue</em></a>. I strongly recommend you to read this article for a better understanding.</p><h3>Assets</h3><p>Styles description you can see in the preparation section. Here is the main JS file for compiling - <strong><em>app.js</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7708fbecf4434a0bed911656b15ebfbd/href">https://medium.com/media/7708fbecf4434a0bed911656b15ebfbd/href</a></iframe><p>Declare custom directive <em>autofocus</em>:</p><pre>directives: {<br>    &#39;autofocus&#39;: {<br>        inserted(el) {<br>            el.focus();<br>        }<br>    }<br>},</pre><h4>Data overview</h4><p>Here are objects for all files or a specific file. Also you can see empty objects for pagination, form data, errors and specific file for editing or deleting.</p><p>In this list we have such boolean type properties as is-video, loading, notification, showConfirm, and modalActive.</p><p>Besides, there are string type properties here: activeTab, filename, attachment and message.</p><h4>Methods</h4><p><strong><em>isActive</em></strong>:</p><pre>isActive(tabItem) {<br>    return this.activeTab === tabItem;<br>},</pre><p>Check if the tab is active.</p><p><strong><em>setActive</em></strong>:</p><pre>setActive(tabItem) {<br>    this.activeTab = tabItem;<br>},</pre><p>Make the tab active.</p><p><strong><em>isCurrentPage</em></strong>:</p><pre>isCurrentPage(page) {<br>    return this.pagination.current_page === page;<br>},</pre><p>Check if the page is active.</p><p><strong><em>fetchFile</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e447dec11686c2d11fe0156350981860/href">https://medium.com/media/e447dec11686c2d11fe0156350981860/href</a></iframe><p>First of all, show loading section. Then send the AJAX request to the server. On success write result data to the file and pagination properties, on error - console.log. And finally hide loading section.</p><p><strong><em>getFiles</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d37a217e85df3263b6ae225d68871c3/href">https://medium.com/media/4d37a217e85df3263b6ae225d68871c3/href</a></iframe><p>The first step is set active tab. The second - fetch all files with a specific type. And at the end check, if active tab is tab with videos.</p><p><strong><em>submitForm</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c39a4bf10a24cf9ee2ae5d87e654d004/href">https://medium.com/media/c39a4bf10a24cf9ee2ae5d87e654d004/href</a></iframe><p>Append name and all file information to the form data. Then send AJAX request to the server with this data (in headers we specify Content-Type of this form for files upload multipart/form-data).</p><p>If success - reset all form data, show notification and fetch all files in active tab.</p><p>If error - show notification with errors and fetch all files in active tab.</p><p><strong><em>addFile</em></strong>:</p><pre>addFile() {<br>    this.attachment = this.$refs.file.files[0];<br>},</pre><p>Attach files. Thanks to the ref attribute we can easily access to the input field where type is file.</p><p><strong><em>prepareToDelete</em></strong>:</p><pre>prepareToDelete(file) {<br>    this.deletingFile = file;<br>    this.showConfirm = true;<br>},</pre><p>Mark a specific file as file for deleting and show custom confirmation.</p><p><strong><em>cancelDeleting</em></strong>:</p><pre>cancelDeleting() {<br>    this.deletingFile = {};<br>    this.showConfirm = false;<br>},</pre><p>Delete the information about the specific file and close custom confirm.</p><p><strong><em>deleteFile</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cff8c9738d1de38c04916f9495e75fe/href">https://medium.com/media/3cff8c9738d1de38c04916f9495e75fe/href</a></iframe><p>AJAX request to the server with a specific file id.</p><p>On success and or error show notification, and then fetch files on current tab with current page.</p><p><strong><em>editFile</em></strong>:</p><pre>editFile(file) {<br>    this.editingFile = file;<br>},</pre><p>Mark a specific file as file for editing.</p><p><strong><em>endEditing</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4c3424f026fad9d7c8ef8a8dcbe8c8c/href">https://medium.com/media/c4c3424f026fad9d7c8ef8a8dcbe8c8c/href</a></iframe><p>Append name, type and extension to the form data and send AJAX request to the server.</p><p>Show notification on success, and then change image without page reloading. Otherwise show notification with errors.</p><p><strong><em>showNotification</em></strong>:</p><pre>showNotification(text, success) {<br>    if (success === true) {<br>        this.clearErrors();<br>    }<br>    <br>    var application = this;<br>    application.message = text;<br>    application.notification = true;<br>    <br>    setTimeout(function() {<br>        application.notification = false;<br>    }, 15000);<br>},</pre><p>Show notification on success or on error. So if success is true — show success notification.</p><p>And then set timeout to hide notification.</p><p><strong><em>showModal</em></strong>:</p><pre>showModal(file) {<br>    this.file = file;<br>    this.modalActive = true;<br>},</pre><p>Show modal window with a specific image.</p><p><strong><em>closeModal</em></strong>:</p><pre>closeModal() {<br>    this.modalActive = false;<br>    this.file = {};<br>},</pre><p>Close modal window.</p><p><strong><em>changePage</em></strong>:</p><pre>changePage(page) {<br>    if (page &gt; this.pagination.last_page) {<br>        page = this.pagination.last_page;<br>    }<br>    <br>    this.pagination.current_page = page;<br>    this.fetchFile(this.activeTab, page);<br>},</pre><p>Allows us to change the page.</p><p><strong><em>resetForm</em></strong>:</p><pre>resetForm() {<br>    this.formData = {};<br>    this.fileName = &#39;&#39;;<br>    this.attachment = &#39;&#39;;<br>},</pre><p>It is as it is. Just reset the form data.</p><p><strong><em>anyError</em></strong>:</p><pre>anyError() {<br>    return Object.keys(this.errors).length &gt; 0;<br>},</pre><p>Check if there are any errors here.</p><p><strong><em>clearErrors</em></strong>:</p><pre>clearErrors() {<br>    this.errors = {};<br>}</pre><p>Clear errors object.</p><h4>Computed</h4><p>Here we generate pages for pagination. So, the <strong><em>pages </em></strong>property contain logic for the pagination (<a href="https://codeburst.io/pagination-with-ajax-request-using-laravel-and-vue-fc584b6fa1ea"><em>Pagination with ajax request using Laravel and Vue</em></a><em> </em>for explanation):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d3b918e55f45d0499ab653dec61eb1/href">https://medium.com/media/39d3b918e55f45d0499ab653dec61eb1/href</a></iframe><h4>Mounted</h4><p>Fetch all the records:</p><pre>mounted() {<br>    this.fetchFile(this.activeTab, this.pagination.current_page);<br>},</pre><p><strong><em>activeTab </em></strong>is image by default and <strong><em>pagination.current_page</em></strong> = 1 by default.</p><h3>Conclusion</h3><p>At the end we have a service that allow us to upload files to the server. These files can be four types: image, audio, video and document. Our system automatically recognize file type and upload file in the personal specific directory.</p><p>Also we have such components as modal window for the specific image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAtRqQjf1BWkvtb7kgVg5g.png" /><figcaption>Modal window for the specific image</figcaption></figure><p>Notifications:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVb5dORG6GKfi32NHNPCXg.png" /><figcaption>Notification on success</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X15Ke3I4ELdWWzptgYcZbw.png" /><figcaption>Notification on error</figcaption></figure><p>Custom confirm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7H_8U_HOVKBA4TfFdP4cMg.png" /><figcaption>Confirm on file deleting</figcaption></figure><p>And pagination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8v2YuO567bpZYqyw7fNK0w.png" /><figcaption>Pagination in action</figcaption></figure><p>Of course here is a lot of work to improve this project. But the first step is done and in the future you can do what you want.</p><p><strong><em>P.S.</em></strong> The source code available on <a href="https://github.com/fl2top/laravel-file-hosting">GitHub</a>. If you have any questions or suggestions write it on the comments. Thank you for the reading!</p><h4>UPDATE</h4><p>Article version you can find in <a href="https://github.com/fl2top/laravel-file-hosting/releases/tag/1.0.0">1.0.0 release</a> on GitHub. But after that code was refactored and now on GitHub you’ll find <a href="https://github.com/fl2top/laravel-file-hosting/releases/tag/1.1.1">release 1.1.1</a>.</p><p>In the last release there were some improvements in the front end:</p><ol><li>Added property <strong><em>savedFile</em></strong></li><li>Changed method <strong><em>editFile</em></strong></li></ol><pre>editFile(file) {<br>    this.editingFile = file;<br>    this.savedFile.type = file.type;<br>    this.savedFile.name = file.name;<br>    this.savedFile.extension = file.extension;<br>}</pre><p>3. Now there are two image lines in the <em>main.blade.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc2146c83cd227104c5cc1a2c3631af/href">https://medium.com/media/2dc2146c83cd227104c5cc1a2c3631af/href</a></iframe><p>Also there are some properties and methods were moved from the <em>FileController.php </em>to the<em> File </em>model.</p><p>And now there are new <em>FileController.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15ec094994f6629bc942cfcdc44bf751/href">https://medium.com/media/15ec094994f6629bc942cfcdc44bf751/href</a></iframe><p>And model <em>File.php</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcb363164af2bb1f997c9f03ed924d9/href">https://medium.com/media/fbcb363164af2bb1f997c9f03ed924d9/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915378c8b2a4" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/upload-and-manage-files-with-laravel-and-vue-915378c8b2a4">Upload and manage files with Laravel and Vue</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pagination with ajax request using Laravel and Vue]]></title>
            <link>https://codeburst.io/pagination-with-ajax-request-using-laravel-and-vue-fc584b6fa1ea?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc584b6fa1ea</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 08:48:39 GMT</pubDate>
            <atom:updated>2021-02-25T19:41:20.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3lBArBfX5h_y6lN_LYQyQ.png" /></figure><p>Let’s see a simple example of pagination with AJAX request using Laravel framework, Vue.js and Bulma css framework.</p><h3>Back end</h3><p>First of all we define our routes in <strong><em>routes/web.php</em></strong>:</p><pre>Route::get(‘/’, function() {<br> return view(‘welcome’);<br>});</pre><pre>Route::get(‘posts’, ‘PostController@index’);</pre><p>Here we can see two routes for: the first route just render our view <strong><em>welcome.blade.php</em></strong>, and the second — define controller and its method.</p><p>The next step is to create model, migration and controller in one artisan command:</p><pre>php artisan make:model Post -mc</pre><p>Now we can define structure of our posts table in our migration file:</p><pre>public function up()<br>{<br>    Schema::create(&#39;posts&#39;, function (Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;string(&#39;title&#39;);<br>        $table-&gt;text(&#39;body&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><blockquote><strong>WARNING!</strong></blockquote><blockquote>If you use MariaDB there is can be a problem to work with DBMS via artisan command. In this case all that you need is using this in <strong><em>AppServiceProvider</em></strong>:</blockquote><pre>public function boot()<br>{<br>    Schema::defaultStringLength(191);<br>}</pre><p>The model we leave unchanged. What considering controller — it has only one method that will be fetching posts from the database and paginate them:</p><pre>class PostController extends Controller<br>{<br>    public function index()<br>    {<br>        $posts = Post::paginate(3);</pre><pre>        $response = [<br>            &#39;pagination&#39; =&gt; [<br>                &#39;total&#39; =&gt; $posts-&gt;total(),<br>                &#39;per_page&#39; =&gt; $posts-&gt;perPage(),<br>                &#39;current_page&#39; =&gt; $posts-&gt;currentPage(),<br>                &#39;last_page&#39; =&gt; $posts-&gt;lastPage(),<br>                &#39;from&#39; =&gt; $posts-&gt;firstItem(),<br>                &#39;to&#39; =&gt; $posts-&gt;lastItem()<br>            ],<br>            &#39;data&#39; =&gt; $posts<br>        ];</pre><pre>        return response()-&gt;json($response);<br>    }<br>}</pre><p>In this case we get only three record on the page. All about pagination in laravel you can see <a href="https://laravel.com/docs/5.5/pagination">here</a>.</p><p>Now we need create seeder:</p><pre>php artisan make:seeder PostsTableSeeder</pre><p>and factory:</p><pre>php artisan make:factory PostFactory</pre><p>You can read about seeding and factories in <a href="https://laravel.com/docs/5.5/seeding">laravel documentation</a>.</p><p><strong><em>PostFactory</em></strong><em> </em>will be generate random text for title and body fields in our posts table:</p><pre>use Faker\Generator as Faker;</pre><pre>$factory-&gt;define(\App\Post::class, function (Faker $faker) {<br>    return [<br>        &#39;title&#39; =&gt; $faker-&gt;title,<br>        &#39;body&#39; =&gt; $faker-&gt;text<br>    ];<br>});</pre><p>And now we can insert 50 row that will be generated by <strong><em>PostFactory</em></strong>. Let’s do it in <strong><em>PostTableSeeder</em></strong>:</p><pre>class PostTableSeeder extends Seeder<br>{<br>    public function run()<br>    {<br>        factory(Post::class, 50)-&gt;create();<br>    }<br>}</pre><h3>Front end</h3><p>Now go to the front end. Here is <strong><em>welcom.blade.php</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89c4c72b00f6356877bef766fc560e6b/href">https://medium.com/media/89c4c72b00f6356877bef766fc560e6b/href</a></iframe><p>As you can see, pagination component will be shown only if we have more than one page. Here we pass <strong>pagination </strong>and <strong>offset </strong>to the <strong><em>PaginationComponent</em></strong>. Also we listen custom event <strong>paginate </strong>on a child component.</p><p>And, finally, <strong><em>PaginationComponent</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44e5d342c6be50446e7bfc2f30e81528/href">https://medium.com/media/44e5d342c6be50446e7bfc2f30e81528/href</a></iframe><p>Template for pagination you can find in <a href="https://bulma.io/documentation/components/pagination/">bulma documentation</a>. We just add two buttons: <em>First page and Last Page</em>.</p><p>Here we get such props as <strong>pagination </strong>and <strong>offset</strong> from parent component.</p><p>Computed property <strong>pages() </strong>contains all pagination logic: it’s generating number visible pages.</p><p>Method <strong>isCurrentPage </strong>return <strong>true</strong> if page is current.</p><p>And obviously the <strong>changePage </strong>method change current page. In this method we also emit parent handler <strong>paginate</strong>.</p><p>Further actions take place in <strong><em>app.js</em></strong>, where we just fetch posts from the server with ajax request using <a href="https://github.com/axios/axios">axios</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44e5d342c6be50446e7bfc2f30e81528/href">https://medium.com/media/44e5d342c6be50446e7bfc2f30e81528/href</a></iframe><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsIMOhQqblRy0k_IY8ejEA.png" /></figure><p><strong><em>P.S.</em></strong> The source code available on <a href="https://github.com/fl2top/laravel-ajax-pagination">GitHub</a>. If you have any questions or suggestions write it on the comment. Thank you for the reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc584b6fa1ea" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/pagination-with-ajax-request-using-laravel-and-vue-fc584b6fa1ea">Pagination with ajax request using Laravel and Vue</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue components with a simple example. For beginners from beginner]]></title>
            <link>https://codeburst.io/vue-components-with-a-simple-example-for-beginners-from-beginner-b0d4ff84aa62?source=rss-a810ec5d1ae4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d4ff84aa62</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[mitrallex]]></dc:creator>
            <pubDate>Sat, 07 Oct 2017 18:58:33 GMT</pubDate>
            <atom:updated>2018-02-02T13:25:37.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*HzcSPfte8sv5_le2f0uFOg.png" /></figure><p>Let’s look at Vue component <strong>Task-list.vue</strong> from <a href="https://medium.com/@fl2top/simple-to-do-application-with-laravel-and-vue-4af28cb007ad">previous article</a> in details. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28fde1bc512bab99735a02ba626ddc0d/href">https://medium.com/media/28fde1bc512bab99735a02ba626ddc0d/href</a></iframe><p>We used single file component in this case. It has <strong>.vue</strong> extension (as you see) and can contain three section:</p><ol><li>&lt;template&gt;&lt;/template&gt;</li><li>&lt;style&gt;&lt;/style&gt;</li><li>&lt;script&gt;&lt;/script&gt;</li></ol><h4>Template</h4><p><em>Reading this section you can keep one eye on the </em><strong><em>Script </em></strong><em>section located below.</em></p><p>Everything begins from adding a task:</p><pre>&lt;div class=&quot;field has-addons&quot;&gt;<br>  &lt;div class=&quot;control is-expanded&quot;&gt;<br>    &lt;input class=&quot;input&quot; type=&quot;text&quot; placeholder=&quot;New task&quot; v-model=&quot;task.body&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;control&quot;&gt;<br>    &lt;a class=&quot;button is-primary&quot; <a href="http://twitter.com/click">@click</a>=&quot;createTask()&quot;&gt;<br>      Add task<br>    &lt;/a&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>And this is our first directive <strong><em>v-model</em></strong>. This directive create a two-way binding on a form input element or a component. We define the <strong>task</strong> in the <strong>data</strong> function in <em>&lt;script&gt;</em> section.</p><p>We can use the <strong><em>v-on </em></strong>(also works with shorthand @: <strong><em>v-on:click == @click</em> </strong>) directive to listen to DOM events and run some JavaScript when they’re triggered. For example on click we call the createTask function, that we define in <em>methods in &lt;script&gt;</em> section:</p><pre>&lt;a class=&quot;button is-primary&quot; <a href="http://twitter.com/click">@click</a>=&quot;createTask()&quot;&gt;<br>  Add task<br>&lt;/a&gt;</pre><p>Now we create our tabs for current and archived tasks:</p><pre>&lt;div class=&quot;tabs is-centered&quot;&gt;<br>  &lt;ul&gt;<br>    &lt;li :class=&quot;{&#39;is-active&#39;:isActive(&#39;current&#39;)}&quot;&gt;<br>      &lt;h3 class=&quot;title&quot;&gt;<br>        &lt;a href=&quot;#&quot; v-on:click.prevent=&quot;fetchTaskList()&quot;&gt;<br>          Current task<br>        &lt;/a&gt;<br>      &lt;/h3&gt;<br>    &lt;/li&gt;<br>    &lt;li :class=&quot;{&#39;is-active&#39;:isActive(&#39;archive&#39;)}&quot;&gt;<br>      &lt;h3 class=&quot;title&quot;&gt;<br>        &lt;a href=&quot;#&quot; v-on:click.prevent=&quot;fetchTaskList(1)&quot;&gt;<br>          Archived tasks<br>        &lt;/a&gt;<br>      &lt;/h3&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>We can pass an object to <strong><em>v-bind:class </em></strong>(shorthand <strong><em>v-bind:class == :class</em></strong>) to dynamically toggle classes. It means the presence of the <em>is-active</em> class will be determined by the truthiness of the method isActive (if isActive function return true class will be <em>is-active</em>).</p><p>Also here you can see postfix <strong><em>.prevent</em></strong> for <strong><em>v-on:click </em></strong>that prevent default action on click. And then <strong><em>v-on:click</em></strong> call the fetchTaskList function:</p><pre>v-on:click.prevent=&quot;fetchTaskList()&quot;</pre><p>That’s it with adding data. Now let’s see the output.</p><p>All our tasks show in this div element:</p><pre>&lt;div class=&quot;card&quot; v-for=&quot;task in list&quot;&gt;&lt;/div&gt;</pre><p>Here is we can see <strong><em>v-for </em></strong>directive. With this directive we can render a list of task based on an array (<em>for each task in the list</em>). We get the <strong>list </strong>array from the <strong>data</strong> function in <em>&lt;script&gt;</em> section.</p><p>In this div element we can use text interpolation using the “Mustache” syntax (double curly braces):</p><pre>&lt;p class=&quot;card-header-title&quot;&gt;<br>  Task {{ task.id }}<br>&lt;/p&gt;</pre><p>The mustache tag will be replaced with the value of the <strong><em>task.id</em></strong> property on the corresponding data object. It will also be updated whenever the data object’s <strong><em>task.id</em></strong> property changes.</p><p>In the next line there is nothing special — prevent default event on click and then call the arhiveTask function:</p><pre>&lt;a href=&quot;#&quot; class=&quot;card-header-icon&quot; aria-label=&quot;more options&quot; v-on:click.prevent=&quot;archiveTask(task.id)&quot;&gt;&lt;/a&gt;</pre><p>But inside this <em>&lt;a&gt;</em> tag we have too much classes definition:</p><pre>&lt;i class=&quot;fa &quot; :class=&quot;{&#39;fa-square-o&#39;: !task.archive,<br>                         check: !task.archive,<br>                         &#39;fa-check-square-o&#39;: task.archive,<br>                         done: task.archive}&quot;  aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;</pre><p>As you can see, <em>&lt;i&gt; </em>tag has <em>fa-square-o </em>(<a href="http://fontawesome.io/">font awesome</a> class) and <em>check </em>classes if <strong><em>task.archive </em></strong>is false, otherwise — <em>fa-check-square-o </em>and <em>done </em>classes<em>.</em></p><p>The next div element isresponsible for the showing or editing the body of the task. Let’s see how it works:</p><pre>&lt;div class=&quot;card-content&quot;&gt;<br>  &lt;div class=&quot;content&quot;&gt;<br>    &lt;p v-if=&quot;task !== editingTask&quot; <a href="http://twitter.com/dblclick">@dblclick</a>=&quot;editTask(task)&quot; v-bind:title=&quot;message&quot;&gt;<br>      {{ task.body }}<br>    &lt;/p&gt;<br>    &lt;input class=&quot;input&quot; v-if=&quot;task === editingTask&quot; v-autofocus <a href="http://twitter.com/keyup">@keyup</a>.enter=&quot;endEditing(task)&quot; <a href="http://twitter.com/blur">@blur</a>=&quot;endEditing(task)&quot; type=&quot;text&quot; placeholder=&quot;New task&quot; v-model=&quot;task.body&quot;&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Here is we can see another directive — <strong><em>v-if</em></strong>. This directive, obviously, allow us to show element if condition is true. So if this task is not editing task — show <em>&lt;p&gt;</em> element that contain body of the task:</p><pre>&lt;p v-if=&quot;task !== editingTask&quot; <a href="http://twitter.com/dblclick">@dblclick</a>=&quot;editTask(task)&quot; v-bind:title=&quot;message&quot;&gt;<br>      {{ task.body }}<br>&lt;/p&gt;</pre><p>Also if you hover mouse on this element you will see title <em>‘Double click for editing.’ </em>. We render this text from the <em>message </em>variable and bind with <strong><em>v-bind:title</em></strong><em>.</em> And it is true! With <strong><em>v-on (shorthand - @) </em></strong>directive we call the <em>editTask</em> function on double click on this element. After double clicking on the <em>&lt;p&gt; </em>element the <em>editingTask</em> will return true, so <em>&lt;p&gt;</em> element will hide and <em>&lt;input&gt;</em> element will show:</p><pre>&lt;input class=&quot;input&quot; v-if=&quot;task === editingTask&quot; v-autofocus <a href="http://twitter.com/keyup">@keyup</a>.enter=&quot;endEditing(task)&quot; <a href="http://twitter.com/blur">@blur</a>=&quot;endEditing(task)&quot; type=&quot;text&quot; placeholder=&quot;New task&quot; v-model=&quot;task.body&quot;&gt;</pre><p>Now we can edit a specific task. For ending editing task just press Enter button:</p><pre><a href="http://twitter.com/keyup">@keyup</a>.enter=&quot;endEditing(task)&quot;</pre><p>or click on any other element on the page except for this <em>&lt;input&gt;:</em></p><pre><a href="http://twitter.com/blur">@blur</a>=&quot;endEditing(task)&quot;</pre><p>But also here we have our own directive <strong><em>v-autofocus</em></strong>, that define that this <em>&lt;input&gt; </em>get focus after double click.</p><p>And at the end of <em>&lt;template&gt; </em>section we have delete button, that prevent default event and call the <em>deleteTask</em> function.</p><pre>&lt;a class=&quot;card-footer-item&quot; v-on:click.prevent=&quot;deleteTask(task.id)&quot;&gt;Delete&lt;/a&gt;</pre><h4>Style</h4><p>But in <strong>Task-list.vue</strong> we have only <em>&lt;template&gt;</em> and <em>&lt;script&gt; </em>sections! So, I think it will be better to move all our styles for this component from <strong>app.scss </strong>(look at <a href="https://medium.com/@fl2top/simple-to-do-application-with-laravel-and-vue-4af28cb007ad">this article</a> for more detail) to <em>&lt;style&gt;</em> section in <strong>Task-list.vue</strong></p><pre>&lt;style scoped&gt;<br>  .task-list .title {<br>    margin: 1rem 0;<br>  }</pre><pre>.task-list .card {<br>    margin: 20px 0;<br>  }</pre><pre>.check {<br>    color: #ff3860;<br>  }</pre><pre>.done {<br>    color: #22c65b;<br>  }</pre><pre>.check:hover {<br>    color: #ff3860;<br>  }</pre><pre>.check:active,<br>  .done:active {<br>    border: none;<br>  }</pre><pre>.done:hover {<br>    color: #22c65b;<br>  }<br>&lt;/style&gt;</pre><p>When a <em>&lt;style&gt;</em> tag has the scoped attribute, its CSS will apply to elements of the current component only. But you can include both scoped and non-scoped styles in the same component:</p><pre>&lt;style&gt;<br>  /* global styles */<br>&lt;/style&gt;</pre><pre>&lt;style scoped&gt;<br>  /* local styles */<br>&lt;/style&gt;</pre><p>Also you can use any css pre-processor.</p><h4>Script</h4><p>Here you can use export default for this module (read more about <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/export">ES Modules</a>).</p><p>At the first register <a href="https://vuejs.org/v2/guide/custom-directive.html">custom directive</a> <strong><em>autofocus </em></strong>locally:</p><pre>directives: {<br>  &#39;autofocus&#39;: {<br>    inserted(el) {<br>      el.focus();<br>    }<br>  }<br>}</pre><p>There is how it works: when the bound element is inserted into the DOM, focus on him:</p><pre>inserted(el) {<br>  el.focus();<br>}</pre><p>The data function return all variables that we need:</p><pre>data() {<br>  return {<br>      message: &#39;Double click for editing.&#39;,<br>      list: [],<br>      task: {<br>        id: &#39;&#39;,<br>        body: &#39;&#39;,<br>        archive: &#39;&#39;<br>      },<br>      editingTask: {},<br>      activeItem: &#39;current&#39;<br>  }<br>}</pre><p>When new Vue instance is created <a href="https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks">(Vue instance lifecycle</a>) call the <em>fetchTaskList</em> function from methods:</p><pre>created() {<br>  this.fetchTaskList();<br>}</pre><p>Now let’s look each function from the methods in details.</p><p><strong><em>fetchTaskList</em></strong></p><p>Get list of the tasks:</p><pre>fetchTaskList(archive = null) {</pre><pre>  if (archive === null) {<br>    var url = &#39;current_tasks&#39;;<br>    this.setActive(&#39;current&#39;);<br>  } else {<br>    var url = &#39;archived_tasks&#39;;<br>    this.setActive(&#39;archive&#39;);<br>  }</pre><pre>  axios.get(url).then(result =&gt; {<br>    this.list = result.data<br>  });<br>},</pre><p>If <em>archive </em>variable is null, we will get current tasks, otherwise — archived tasks.</p><p>Here and below we use <a href="https://www.npmjs.com/package/axios">axios</a> for AJAX requests.</p><p><strong><em>isActive</em></strong></p><p>Return true, if the <em>menuItem</em> is active:</p><pre>isActive(menuItem) {<br>  return this.activeItem === menuItem;<br>},</pre><p><strong><em>setActive</em></strong></p><p>Set menuItem as active:</p><pre>setActive(menuItem) {<br>  this.activeItem = menuItem;<br>},</pre><p><strong><em>createTask</em></strong></p><p>Obviously, it’s function for creating new task:</p><pre>createTask() {<br>  axios.post(&#39;create_task&#39;, this.task).then(result =&gt; {<br>    this.task.body = &#39;&#39;;<br>    this.fetchTaskList();<br>  }).catch(err =&gt; {<br>    console.log(err);<br>  });<br>},</pre><p>Send post AJAX request to <strong>create_task </strong>url. Fetch task list on success or console.log on error.</p><p><strong><em>editTask</em></strong></p><p>Mark specific task as editing task:</p><pre>editTask(task) {<br>  this.editingTask = task;<br>},</pre><p>Now we will work with this task for editing.</p><p><strong><em>endEditing</em></strong></p><p>When we end edit task:</p><pre>endEditing(task) {<br>  this.editingTask = {};<br>  if (task.body.trim() === &#39;&#39;) {<br>    this.deleteTask(task.id);<br>  } else {<br>    axios.post(&#39;edit_task&#39;, task).then(result =&gt; {<br>      console.log(&#39;success!&#39;)<br>    }).catch(err =&gt; {<br>      console.log(err);<br>    });<br>  }<br>},</pre><p>First of all we clean <em>editingTask</em> variable. Then check if body of the task is empty — delete this task, otherwise send post AJAX request to <strong>edit_task </strong>url. Console.log(“success!”) on success or console.log(err) on error.</p><p><strong><em>deleteTask</em></strong></p><p>Deleting specific task by sending post AJAX request to <strong>delete_task</strong> url:</p><pre>deleteTask(id) {<br>  axios.post(&#39;delete_task/&#39; + id).then(result =&gt; {<br>    this.fetchTaskList();<br>  }).catch(err =&gt; {<br>    console.log(err);<br>  });<br>},</pre><p>Fetch task list on success or console.log on error.</p><p><strong><em>archiveTask</em></strong></p><p>Mark task as archived, or mark as current:</p><pre>archiveTask(id) {<br>  axios.post(&#39;archive_task/&#39; + id).then(result =&gt; {<br>    this.fetchTaskList();<br>  }).catch(err =&gt; {<br>    console.log(err);<br>  });<br>}</pre><p>Send post AJAX request to <strong>archive_task </strong>url. Fetch task list on success or console.log on error.</p><h4>Adding component to the main app.js file</h4><p>The main thing here is adding component before creating new Vue instance.</p><p>In <em>html</em> file define div element with id = app:</p><pre>&lt;div id=&#39;app&#39; class=&quot;container&quot;&gt;<br>  &lt;task-list&gt;&lt;/task-list&gt;<br>&lt;/div&gt;</pre><p>In <em>app.js </em>file add component and then create new Vue instance:</p><pre>Vue.component(&#39;task-list&#39;, require(&#39;./components/Task-list.vue&#39;));</pre><pre>const app = new Vue({<br>    el: &#39;#app&#39;<br>});</pre><h4>Conclusion</h4><p>Separation into this three sections give us:</p><ol><li>Complete syntax highlighting in <em>&lt;template&gt;</em> section.</li><li>Common JS modules in <em>&lt;script&gt;</em> section.</li><li>And, as you see, scoped <em>&lt;style&gt;</em> section.</li></ol><p>There is no doubt that it’s very convenient.</p><p>Thank you for the reading! I hope that this example will be helpful for you and it’s make your learning some easier.</p><p><strong><em>P.S.</em></strong><em> I am in the learning process right now too, so help me please by leaving a comment with question or suggestion.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d4ff84aa62" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/vue-components-with-a-simple-example-for-beginners-from-beginner-b0d4ff84aa62">Vue components with a simple example. For beginners from beginner</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>