<?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 Kazem Mirzaei on Medium]]></title>
        <description><![CDATA[Stories by Kazem Mirzaei on Medium]]></description>
        <link>https://medium.com/@kazemmdev?source=rss-1528838ac4fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ofRz35AFQUOaYNhElvLKQA.jpeg</url>
            <title>Stories by Kazem Mirzaei on Medium</title>
            <link>https://medium.com/@kazemmdev?source=rss-1528838ac4fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kazemmdev/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[Most Developers Use AI. Few Actually Lead It.]]></title>
            <link>https://kazemmdev.medium.com/most-developers-use-ai-few-actually-lead-it-6d662bcb071c?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d662bcb071c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 17:30:49 GMT</pubDate>
            <atom:updated>2026-02-26T17:30:49.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UDfyjdLnioDIeEqG" /><figcaption>Photo by <a href="https://unsplash.com/@dkomow?utm_source=medium&amp;utm_medium=referral">Daniil Komov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AI is now embedded in modern development workflows.</p><p>Code generation, refactoring, documentation, debugging — it’s all accelerated.</p><p>But after integrating AI deeply into real production systems, I’ve noticed something important:</p><p>The difference between average results and exceptional results is rarely the model.</p><p>It’s how the engineer guides it.</p><p>Switching from one model to another rarely transforms mediocre output into great engineering.</p><p>Clear thinking does.</p><p>Let’s break down what actually makes the difference.</p><h3>1. Clarity Beats Verbosity</h3><p>Many developers assume that giving AI more information improves results.</p><p>In practice, unfocused information degrades results.</p><p>AI performs best when the task is:</p><ul><li>Clearly defined</li><li>Narrowly scoped</li><li>Explicit in constraints</li></ul><p>For example, compare:</p><blockquote><em>Improve this code.</em></blockquote><p>vs.</p><blockquote><em>Refactor this Laravel service to reduce database queries, avoid N+1 issues, and maintain backward compatibility with existing API responses.</em></blockquote><p>The second instruction narrows the solution space.The first invites ambiguity.</p><p>More context is not better.</p><p>Relevant context is better.</p><p>Precision scales. Noise compounds.</p><h3>2. Context Is a Tool — Not a Dumping Ground</h3><p>In large codebases, especially microservice or modular architectures, context selection becomes critical.</p><p>Attaching entire folders or referencing loosely related modules “just in case” introduces ambiguity.</p><p>Instead:</p><ul><li>Provide only the files directly involved.</li><li>Clarify relationships explicitly.</li><li>Define what must not change.</li></ul><p>Strong engineers curate context before passing it to AI.</p><p>AI systems are pattern predictors.</p><p>The cleaner the pattern space, the cleaner the output.</p><h3>3. Think → Plan → Prompt</h3><p>One of the biggest productivity leaks in AI-assisted workflows is skipping the thinking phase.</p><p>Prompting should not be reactive.</p><p>Before writing the instruction:</p><ol><li>Define the outcome.</li><li>Identify constraints.</li><li>Break the task into steps.</li><li>Decide the evaluation criteria.</li></ol><p>Then prompt.</p><p>When teams complain about needing constant follow-ups and corrections, the issue often isn’t the tool — it’s the absence of upfront structure.</p><p>Planning reduces iterations.</p><p>Structure reduces friction.</p><p>Friction slows teams.</p><h3>4. Share the Edge Cases Early</h3><p>Engineers sometimes “test” AI by withholding known complexity:</p><ul><li>Hidden edge cases</li><li>Performance constraints</li><li>Backward compatibility requirements</li></ul><p>This is counterproductive.</p><p>AI is not a junior developer you’re evaluating.</p><p>It’s an execution engine.</p><p>If you know there’s a race condition risk — say it.</p><p>If the function must remain pure — state it.</p><p>If latency must stay under 100ms — include it.</p><p>The more explicit the constraints, the stronger the output.</p><h3>5. Direct the Tooling Layer</h3><p>Modern AI coding agents can:</p><ul><li>Execute terminal commands</li><li>Traverse repositories</li><li>Refactor across modules</li><li>Run linters or formatters</li><li>Generate migration scripts</li></ul><p>But they don’t automatically choose your preferred path.</p><p>If the solution should:</p><ul><li>Use a specific package</li><li>Follow a specific architectural pattern</li><li>Respect existing domain boundaries</li></ul><p>State it clearly.</p><p>Leadership applies to tools as well.</p><h3>The Real Shift</h3><p>The narrative around AI often focuses on replacement.</p><p>In practice, what’s happening is amplification.</p><p>AI amplifies:</p><ul><li>Clear thinking</li><li>Structured engineering</li><li>Good architecture</li><li>Strong constraint design</li></ul><p>It also amplifies:</p><ul><li>Ambiguity</li><li>Poor planning</li><li>Shallow understanding</li></ul><blockquote>The tool is neutral. Your thinking is not.</blockquote><p>The skill that matters most today isn’t “knowing how to use AI.”</p><p>It’s knowing how to steer it.</p><p>The engineers who master this won’t just ship faster.</p><p>They’ll design better systems — because their thinking improves before their velocity does.</p><p>And in the long run, thinking always compounds more than speed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d662bcb071c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: A Practical Guide for Seeders and Factories]]></title>
            <link>https://kazemmdev.medium.com/laravel101-a-practical-guide-for-seeders-and-factories-5e5dffdc2ffd?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5dffdc2ffd</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel101]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 08:02:58 GMT</pubDate>
            <atom:updated>2023-08-31T08:02:58.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>During the development process, there are times when we need to evaluate the functionality of a system by using data. In Laravel, we have two useful tools called seeders and factories that help us generate random data. In this article, we’ll explore these tools and learn how to use them effectively.</p><p>The factory class in Laravel acts like a factory that generates random data for our database tables. If you navigate to the database/factories directory in your project, you’ll find a class called UserFactory:</p><pre>class UserFactory extends Factory<br>{<br>    public function definition(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; fake()-&gt;name(),<br>            &#39;email&#39; =&gt; fake()-&gt;unique()-&gt;safeEmail(),<br>            &#39;email_verified_at&#39; =&gt; now(),<br>            &#39;password&#39; =&gt; &#39;$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi&#39;, // password<br>            &#39;remember_token&#39; =&gt; Str::random(10),<br>        ];<br>    }<br>}</pre><p>In each factory class, there is an important function called definition that specifies how each attribute should be filled out. To accomplish this, Laravel utilizes a powerful package called <a href="https://github.com/FakerPHP/Faker"><strong>fakerPHP</strong></a>, which can generate random data such as names, sentences, paragraphs, and even images. You can find more information about the helper functions and features of this package at the following link.</p><p><a href="https://fakerphp.github.io/">FakerPHP / Faker</a></p><p>Another point in UserFactory class is that the string that is considered a fixed password is the hashed word “password”.</p><p>Laravel includes a variety of global helper PHP functions, and one of them is called Str. This helper function is useful for working with strings, such as generating random strings. You can refer to the documentation for this helper function at <a href="https://laravel.com/docs/8.x/helpers#strings-method-list"><strong>here</strong></a>.</p><p>Now, let’s get back to our project and generate a factory for our tags. To create a factory, we can use the following artisan command:</p><pre>php artisan make:factory TagFactory</pre><p>It’s generally recommended to use a singular name for factory classes. However, if you want to specify the model while generating the factory, you can use the “-m” option in the command, like this:</p><pre>php artisan make:factory TagFactory -m Tag</pre><p>In our Tag model, we only have a simple “name” attribute, which can be defined as follows:</p><pre>use Illuminate\Database\Eloquent\Factories\HasFactory;<br><br>class Tag extends Model<br>{<br>    use HasFactory;<br>}</pre><p>Once we have set up the factory, we can use it to create instances of our model. To do this, simply call the factory method whenever you want to create a model instance.</p><p>You can also control the number of random data entries you want to generate. You can achieve this by using either the factory function or the count function. For example, if you want to create 5 random tags, you can use the following code:</p><pre>Tag::factory(5)-&gt;create();</pre><p>Furthermore, it’s possible to define a specific attribute with a desired value while generating the data. For instance, if you want to create 5 users with the name “test,” but you don’t care about the other attributes, you can use the following code:</p><pre>User::factory(5)-&gt;create([&#39;name&#39; =&gt; &#39;test&#39;]);</pre><p>In our project, we currently have two factories for our user and tag models. Now, we need to create another factory for our task model.</p><p>When defining the factory model, it is important to consider the relational model. In our task model, each task is associated with a user. So, what we want to achieve is creating a random task with the id of a given user.</p><p>However, during testing your application, there might be situations where no user has been created in the environment. In such cases, generating a random user could be a viable solution. To accomplish this, you can use factory model again just like bellow:</p><pre>public function definition(): array<br>{<br>    return [<br>        &quot;title&quot; =&gt; fake()-&gt;sentence(),<br>        &quot;description&quot; =&gt; fake()-&gt;paragraph(),<br>        &quot;expired_at&quot; =&gt; fake()-&gt;dateTimeThisMonth(),<br>        &quot;user_id&quot; =&gt; User::factory(),<br>    ];<br>}</pre><p>If you run the code in Tinker, you will notice that a new user has been created for the task model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*mb0qOikbjxkFxJEF7otoxw.png" /></figure><p>Also we have the option to specify a user_id when generating a task. However, I suggest refactoring the code to utilize the users that are likely to already exist in database:</p><pre>public function definition(): array<br>{<br>    return [<br>        &quot;title&quot; =&gt; fake()-&gt;sentence(),<br>        &quot;description&quot; =&gt; fake()-&gt;paragraph(),<br>        &quot;expired_at&quot; =&gt; fake()-&gt;dateTimeThisMonth(),<br>        &quot;user_id&quot; =&gt; User::query()-&gt;inRandomOrder()-&gt;first()?-&gt;id ?? <br>           User::factory(),<br>    ];<br>}</pre><p>To generate random data more efficiently in Laravel, we have a better solution than using Tinker. It’s called a seeder.</p><p>In the database/seeders directory, you will find a class named DatabaseSeeder, which allows us to manage the generation of random data.</p><p>Let&#39;s update the DatabaseSeeder class as shown below, and then execute an artisan command to run this function.</p><pre>class DatabaseSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        Task::factory()-&gt;create();<br>    }<br>}</pre><p>And here is the artisan command for seeding:</p><pre>php artisan db:seed</pre><p>That’s it!</p><p>With Seeder, we can easily create a random task record in our database using artisan. Additionally, we have the flexibility to create multiple seeders for different scenarios. To create a seeder, you simply need to run php artisan make:seed &lt;seeder-name&gt; command.</p><p>Now, let’s create a TaskSeeder that generates 5 random task records, with each task associated with two random tags:</p><pre>namespace Database\Seeders;<br><br>use App\Models\Tag;<br>use App\Models\Task;<br>use Illuminate\Database\Seeder;<br><br>class TaskSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        Task::factory(5)-&gt;hasTags(2)-&gt;create();<br>    }<br>}</pre><p>To run this seeder, you can use the artisan command by specifying your desired seed class.</p><pre>php artisan db:seed TaskSeeder</pre><p>Or you can use call method inside DatabaseSeeder to execute your seed classes:</p><pre>class DatabaseSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        $this-&gt;call(TaskSeeder::class);<br>    }<br>}</pre><h4>Initial data model</h4><p>Well, sometimes there are certain values that are need to be initialized, such as the status of an article (e.g., published or draft) or the status of a transaction (e.g., paid or non-payment).</p><p>I want to apply a similar approach to tags in this project. We have a couple of options to achieve this.</p><p>One option is to store the initial values in a configuration file. To do this, we can create a PHP file called “defaults” at the specified config path and define the desired values there:</p><pre>&lt;?php<br><br>return [<br>    &#39;tags&#39; =&gt; [&#39;php&#39;, &#39;laravel&#39;, &#39;develop&#39;, &#39;backend&#39;]<br>];</pre><p>We can then initialize these values using a migration file.</p><p>Alternatively, we can initialize these values using a seeder. This means we would define a seeder like TagSeeder that populates the default value in the database.</p><p>Both approaches work, but I prefer to use seeder because it’s more clear:</p><p>Let’s define TagSeeder and initialize it’s values:</p><pre>class TagSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        foreach (config(&#39;defaults.tags&#39;) as $value) {<br>            Tag::firstOrCreate([&#39;name&#39; =&gt; $value]);<br>        }<br>    }<br>}</pre><p>As you can see, the helper function config in Laravel is utilized to retrieve static information from config files.</p><p>Here I use firstOrCreate method which adds a new tag record only if it hasn’t been previously added.</p><p>Great! Now, let’s all come together and work on implementing a scenario like the one described below inside our TaskSeeder:</p><pre>namespace Database\Seeders;<br><br>use App\Models\Tag;<br>use App\Models\Task;<br>use App\Models\User;<br>use Illuminate\Database\Seeder;<br><br>class TaskSeeder extends Seeder<br>{<br>    public function run(): void<br>    {<br>        // create a user with specified credentials<br>        $user = User::factory()-&gt;create([&#39;email&#39; =&gt; &#39;test@test.dev&#39;]);<br><br>        // init tag with defined value<br>        $this-&gt;call(TagSeeder::class);<br><br>        // create 5 random tasks for the user<br>        $tasks = Task::factory(5)-&gt;create([&#39;user_id&#39; =&gt; $user-&gt;id]);<br><br>        // assosiate each generated tasks with 2 predefined tags<br>        foreach ($tasks as $task) {<br>            $tags = Tag::query()-&gt;inRandomOrder()-&gt;take(2)-&gt;pluck(&#39;id&#39;);<br>            $task-&gt;tags()-&gt;attach($tags);<br>        }<br>    }<br>}</pre><p>Now let’s rebuild our database and fill it with this defined seeder. To rebuild the database you can run migrate:fresh artisan command which will drop all tables and re-run all of your migrations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*2jhwx56vpJcnriD-Y-M57Q.png" /></figure><p>And if you login with the user you’ll see the tasks generated successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDw11ojUj3j-jEvVbpFSRA.png" /></figure><p>I hope this explanation clarifies the process of using seeders and factories in Laravel. If you have any further questions, feel free to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5dffdc2ffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Exploring Efficient Task Management with Many-to-Many Relationships and Tags]]></title>
            <link>https://kazemmdev.medium.com/laravel101-exploring-efficient-task-management-with-many-to-many-relationships-and-tags-a1504b7008fc?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1504b7008fc</guid>
            <category><![CDATA[blade]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel101]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 08:07:34 GMT</pubDate>
            <atom:updated>2023-08-28T08:07:34.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>Great to have you back! In our previous article, we talk about associating different models and defining relationships within our Laravel application. The best part is that now every user in our project can have personalized tasks.</p><p>In this new article, we’re going to take things a step further and explore the <strong>many-to-many</strong> relationship. We’ll introduce a brand new model called tags, which will enable each task in our application to have multiple tags.</p><p>But wait, there’s more! In this article, we&#39;re also going to create a fantastic search select blade component, designed to make working with tags inside our forms. So get ready, because we’re about to dive into some seriously exciting stuff!</p><h3>Create a search select input in blade</h3><p>Now, let’s talk about a new feature I’ve decided to add: a search select input for adding and selecting tags within the task forms. There might be some packages available that can help with this in the application, but let’s start by implementing it using pure JavaScript.</p><p>So, let’s begin!</p><p>First, I created a simple input component for searching text, located in the common directory of our blade components. Then, I added this input component to our create tasks view, as shown in the following picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTWyczpK9Z9zVadXgFX1Tw.png" /></figure><p>Now, if we want to work with pure JavaScript within our common input, we usually need to define all the JavaScript functions within our app.js inside resources/js directory. However, there’s a more convenient way to do this that I prefer, and that is by using a stacked scripts. To achieve this, we have another helpful function within the blade syntax called push. You can use it like this:</p><pre>@push(&#39;scripts&#39;)<br>&lt;script type=&quot;module&quot;&gt;<br>    // Your JavaScript code goes here<br>&lt;/script&gt;<br>@endpush</pre><p>By using this syntax, you can define your script inside the @push(&#39;scripts&#39;) and @endpush tags, and it will be treated as a module. This makes it easier to manage and organize your JavaScript code within your application.</p><p>However, right now these scripts won’t work. In order to bring them to life, we need to add the stacked scripts inside our main layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PezGTBWQo3SNKcwcwKrRyw.png" /></figure><p>Now if you open your console inside your browser you’ll see that our script works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5hTvpHTz5FEXIXClNuecw.png" /></figure><p>Right now, the first step is to listen to every change and character that the user enters in the input field. To achieve this, you need to assign an event listener to the input element.</p><p>To see this in action, you can add the following code snippet to your scripts. When you run it, you’ll notice that every character you enter in the input will be logged to your console:</p><pre>@push(&#39;scripts&#39;)<br>&lt;script type=&quot;module&quot;&gt;<br>    let tagSearchInput = document.getElementById(&quot;search-tag&quot;);<br><br>    tagSearchInput.addEventListener(&quot;input&quot;, async function (e) {<br>        console.log(tagSearchInput.value);<br>    });<br>&lt;/script&gt;<br>@endpush</pre><p>Now, let’s move on to the next step, which is finding all the tags based on the search input.</p><p>But wait we don’t even define our tag model inside our application! It’s actually quite simple! All you need to do is run the following command, and it will take care of creating the model, migration, and controller for you:</p><pre>php artisan make:model Tag -mc</pre><p>This model is straightforward because it only has one attribute, which is the name. So, update the migration file by adding a simple name column. Similarly, update the request file as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnneyXUKMhn5FclwHI0XJg.png" /></figure><p>Finally, let’s move back to the controller because this is where the new things happen, and we need to work on it.</p><p>First, let’s utilize our index function in a slightly different way. Instead of simply listing all the tags in the view, we’ll modify it to return a JSON response. This will allow us to retrieve all the data in our JavaScript code:</p><pre>public function index()<br>{<br>   return response()-&gt;json([<br>        &#39;tags&#39; =&gt; []<br>   ]);<br>}</pre><p>Then we need to search inside our tags records to find tags based on searching input. To accomplish this, we can utilize a commonly used syntax in Laravel for searching within model. Laravel provides a useful function called where() that allows us to retrieve specific records from our database tables based on specific attributes or columns.</p><p>For instance, if we want to find a tag where its name is “job”, the query would look like this:</p><pre>$tag = Tag::where(&#39;name&#39;, &#39;job&#39;)-&gt;get();</pre><p>Don’t forget to use get() at the end to execute the SQL command.</p><p>Now, what if we want to find all the tags that have a name containing the specified letter or letters? Here we use LIKE as a 2nd parameter and `%` at the beginning and end of our search key. For instance:</p><pre># all tags start with a &#39;s&#39;<br>$tags = Tag::where(&#39;name&#39;, &#39;LIKE&#39;, &#39;s%&#39;)-&gt;get();<br><br># all tags end with a &#39;s&#39;<br>$tags = Tag::where(&#39;name&#39;, &#39;LIKE&#39;, &#39;s%&#39;)-&gt;get();<br><br># all tags contains a &#39;s&#39;<br>$tags = Tag::where(&#39;name&#39;, &#39;LIKE&#39;, &#39;%s%&#39;)-&gt;get();</pre><p>So our index function could be look like bellow:</p><pre>public function index()<br>{<br>    $query = Tag::where(&#39;name&#39;, &#39;LIKE&#39;, &quot;%&quot; . request(&#39;name&#39;) . &quot;%&quot;)-&gt;get();<br>    return response()-&gt;json($query);<br>}</pre><p>That’s it! By using this syntax, we can easily search and retrieve the desired tags from our database.</p><p>Now Lets define the new route:</p><pre>Route::get(&#39;tags&#39;, [TagController::class, &#39;index&#39;])-&gt;name(&#39;tags.search&#39;);</pre><p>As you see in following pic I just add some sample data and make a request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*O-a1F52bwEGEXeSXB4oEzA.png" /></figure><p>Well, let’s see how we can use it in JavaScript. To make the HTTP request, we can use a popular package called <a href="https://axios-http.com/"><strong>Axios</strong></a>. The good news is that Axios is already installed by default in Laravel. However, if you don’t have it, you can easily install it using the following command:</p><pre>npm install axios</pre><p>Once you have Axios set up, let’s go back to our JavaScript code and make the request:</p><pre>let tagSearchInput = document.getElementById(&quot;search-tag&quot;);<br><br>tagSearchInput.addEventListener(&quot;input&quot;, async function (e) {<br>    const response = await axios.get(`/tags?name=${tagSearchInput.value}`);<br>    console.log(response.data);<br>});</pre><p>First, Let me explain what “async” and “await” mean in the code. In simple word, think of them as listeners that wait for the result of a request at a specific line.</p><p>Now, we need to display the list of results from our query. To achieve this, we can add an HTML element and populate the list with all the found items.</p><pre>&lt;script type=&quot;module&quot;&gt;<br>    let tagSearchInput = document.getElementById(&quot;search-tag&quot;);<br>    let tagSearchList = document.getElementById(&quot;search-tag-list&quot;);<br><br>    tagSearchInput.addEventListener(&quot;input&quot;, async function (e) {<br>        const response = await axios.get(`/tags?name=${tagSearchInput.value}`);<br><br>        if (response.data.length) {<br>            tagSearchList.classList.remove(&quot;hidden&quot;);<br><br>            // remove all item inside list<br>            while (tagSearchList.firstChild) {<br>                tagSearchList.removeChild(tagSearchList.firstChild);<br>            }<br><br>            // add found tags inside the list<br>            response.data.forEach((tag) =&gt; {<br>                let li = document.createElement(&quot;li&quot;);<br>                li.appendChild(document.createTextNode(tag.name));<br>                li.className = &quot;tag-list-item&quot;;<br>                // todo: uncomment after add tagSelected()<br>                // li.onclick = () =&gt; tagSelected(tag);<br>                tagSearchList.appendChild(li);<br>            });<br>        } else tagSearchList.classList.add(&quot;hidden&quot;);<br>    });<br>&lt;/script&gt;</pre><p>The process involves iterating through the results. If there is any data, our item list is displayed, and we append a list of found tags to our search list.</p><p>Now, we need to implement click functionality for each tag item in the list. When a tag item is clicked, its tag id should be appended to a designated input field. This input field has a specific id, such as tags-select and its purpose is to store the selected tags within our form. We will utilize this input field when submitting the selected tags along with the task creation.</p><p>To achieve this, I have added three HTML elements as shown in the picture. The first element is an input field with the id tags-select, The second element is an unordered list (ul) which serves as the parent container for our search result tags that are listed. The third element is a div that visually represents the currently selected tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZfHsVulChmbYMHXD89X4A.png" /></figure><p>Next, when a user clicks on a tag item in the list, we want to perform the following actions:</p><ol><li>Create and append an element that represents the selected tag to the tags-select-list Additionally, we add a close button element, which we will later implement its functionality.</li><li>Trigger another function that updates our tags-select input field by adding the id of the selected tag.</li><li>Hide the dropdown list that displays the search results.</li><li>Finally, clear the tag search input element to prepare it for adding another tag.</li></ol><p>Here is the function that handles the click event for each listed tag:</p><pre>const tagSelected = (tag) =&gt; {<br>    let span = document.createElement(&quot;span&quot;);<br>    span.id = tag.id;<br>    span.className = &quot;tag-select-item&quot;;<br><br>    let closeBtn = document.createElement(&quot;i&quot;);<br>    // todo: uncomment after add removeSelectedTag()<br>    // closeBtn.onclick = () =&gt; removeSelectedTag(span);<br>    closeBtn.appendChild(document.createTextNode(&#39;×&#39;));<br>    <br>    span.appendChild(closeBtn);<br>    span.appendChild(document.createTextNode(tag.name));<br><br>    tagSelectWrap.appendChild(span);<br>    tagSearchList.classList.add(&quot;hidden&quot;);<br><br>    tagSearchInput.value = &quot;&quot;;<br>    tagSelectInput.value = inputTag(parseInt(tag.id));<br>}</pre><p>And this is the function that updates our tags-select input field:</p><pre>function inputTag(tagId) {<br>    let tags = tagSelectInput.value.length<br>        ? JSON.parse(tagSelectInput.value)<br>        : [];<br>    if (tags.includes(tagId)) {<br>        const indexToRemove = tags.indexOf(tagId);<br>        tags.splice(indexToRemove, 1);<br>        tags = JSON.stringify(tags);<br>    } else {<br>        tags.push(tagId);<br>        tags = JSON.stringify(tags);<br>    }<br>    return tags;<br>}</pre><p>Here we have to convert array of selected tags id to string since our input accept string value.</p><p>Now, let’s discuss the functionality for removing selected tags. When a user clicks on the close button, the corresponding element needs to be removed from both the tags-select-list and our input field. Here is the code for the removal functionality:</p><pre>const removeSelectedTag = (el) =&gt; {<br>    tagSelectInput.value = inputTag(parseInt(el.id));<br>    tagSelectWrap.removeChild(el);<br>}</pre><p>Amazing let see our fantastic result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*fgLib4y1tvUQCyOg.gif" /></figure><p>The final step is to implement the functionality for adding a new tag when the user presses Enter and the entered tag is not found in our existing records. In this case, we will send the entered tag to the server and store it as a new tag. As a result, we will repeat the entire process of clicking on a list item for the newly added tag.</p><p>To add a new tag, you simply need to include a store function inside the tag controller. Here is how the store function can be implemented:</p><pre>public function store(StoreTagRequest $request)<br>{<br>    $tag = Tag::create($request-&gt;validated());<br>    return response()-&gt;json($tag);<br>}</pre><p>To ensure that everything is set up correctly, please make sure to add the appropriate route and a simple StoreTagRequest class. We have covered this step earlier, and it is relatively straightforward.</p><p>Now let’s return to our search select input and handle the Enter key events. First, we need to check if there are no tags in our records. If there are no existing tags, we will proceed to store a new tag using the following steps:</p><pre>tagSearchInput.addEventListener(&quot;keydown&quot;, async function (e) {<br>    if (e.key === &quot;Enter&quot;) {<br>        e.preventDefault();<br><br>        const response = await axios.get(<br>            `/tags?name=${tagSearchInput.value}`<br>        );<br><br>        if (!response.data.length) {<br>            const { data } = await axios.post(&quot;/tags&quot;, {<br>               name: tagSearchInput.value<br>            });<br>            tagSelected(data);<br>        }<br>    }<br>});</pre><p>Now, we have the exciting capability of adding new tags within our app! Isn’t that amazing?</p><p>Well, Let’s return to the task creation process. Here, we simply need to retrieve the entered tags from the input fields when the request is sent.</p><p>let’s proceed with updating our taskStoreRequest to include selected tags:</p><pre>public function rules(): array<br>{<br>    return [<br>        &#39;title&#39; =&gt; &#39;required|min:3|max:120&#39;,<br>        &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>        &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>    ];<br>}<br><br><br>public function validated($key = null, $default = null)<br>{<br>    if ($key == &#39;tags&#39;) return json_decode(request(&#39;tags&#39;));<br><br>    return $this-&gt;validator-&gt;validated();<br>}</pre><p>I have just refactored the validated method to convert a string of ids into an array of IDs (<em>We cannot merge because merging could lead to conflicts, as there is no column named “tags” inside the tasks model</em>).</p><p>Now, let&#39;s test its functionality by using two given tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLc-zpEoo132trNtpabuiQ.png" /></figure><p>That’s it!</p><h4>Store a Task with given tags</h4><p>Now how to relates this tags to our tasks?</p><p>As I mentioned before, we need a way to manage the relationship between tags and tasks. In a previous article, we discussed this topic you can find out here:</p><p><a href="https://kazemmdev.medium.com/laravel101-exploring-entity-model-relationships-ad4393cef07f">Laravel101: Exploring Entity-Model Relationships</a></p><p>To define the relationship between tags and tasks, we’ll need another table that will record all the connections between these models. This middle table will have two main attributes, and those are the id of each model.</p><p>So, let’s get started and define the table using a migration:</p><pre>php artisan make:migration create_tag_task_table</pre><p>And this is our migration setup:</p><pre>Schema::create(&#39;tag_task&#39;, function (Blueprint $table) {<br>    $table-&gt;foreignId(&#39;tag_id&#39;)-&gt;constrained()-&gt;cascadeOnDelete();<br>    $table-&gt;foreignId(&#39;task_id&#39;)-&gt;constrained()-&gt;cascadeOnDelete();<br>});</pre><p>Right now we need to define relation function for both model that is is incredibly useful and includes many helpful functions that make working with relations in Laravel models straightforward. For both models, we need to declare that each model belongs to the other one.</p><pre>class Task extends Model<br>{<br>    public function tags()<br>    {<br>        return $this-&gt;belongsToMany(Tag::class);<br>    }<br><br>    // ...<br>}<br><br><br>class Tag extends Model<br>{<br>    public function tasks()<br>    {<br>        return $this-&gt;belongsToMany(Task::class);<br>    }<br><br>    // ...<br>}</pre><p>Let’s back to our controller where we need to define relation between created task and selected tags, Here we will use another function call attach just like bellow:</p><pre>public function store(StoreTaskRequest $request)<br>{<br>    $task = auth()-&gt;user()-&gt;tasks()-&gt;create($request-&gt;validated());<br><br>    $task-&gt;tags()-&gt;attach($request-&gt;validated(&#39;tags&#39;));<br><br>    return redirect(&quot;/tasks&quot;, 201);<br>}</pre><p>As you notice after selecting some tags and post store request to server you will notice that a created task is associated with the chosen tags.</p><h4>Update a task’s tags</h4><p>Now what’s about updating tags for a given task,</p><p>The main requirement is to enable the select input using the provided tags. Fortunately, in the Laravel blades, there is a useful feature called “props” that allows for the insertion of variables within components. In our project, we need to define a tags variable, with a default value of null. This will allow us to utilize the component effectively:</p><pre>@props([ &#39;tags&#39; =&gt; null ])</pre><p>Then we need to add selected tags to tags-select input:</p><pre>&lt;input <br>  type=&quot;text&quot; <br>  name=&quot;tags&quot;<br>  id=&quot;tags-select&quot; <br>  value=&quot;{{ isset($tags) ? $tags-&gt;pluck(&#39;id&#39;) : &#39;&#39;}}&quot;<br>  hidden<br>&gt;</pre><p>And show selected tags inside our tags-select-list :</p><pre>&lt;div class=&quot;flex flex-wrap space-x-1&quot; id=&quot;tags-select-list&quot;&gt;<br>    @forelse($tags ?? [] as $tag)<br>        &lt;span id=&quot;{{ $tag-&gt;id }}&quot; class=&quot;tag-select-item&quot;&gt;<br>          &lt;i&gt;×&lt;/i&gt;{{ $tag-&gt;name }}<br>        &lt;/span&gt;<br>    @empty<br>    @endforelse<br>&lt;/div&gt;</pre><p>As you can see, the forelse is used in cases where there may be an empty list. You can also use a simple foreach loop along with an if statement, but the forelse provides a simpler alternative.</p><p>Now, you can use this component into our edit view. When you do so, you will notice that all the selected tags are displayed correctly. However, there is one small thing that still needs to be addressed: the closing functionality for these tags.</p><p>In this situation, all we need to do is search within our list. If any span elements are found, we can assign the close handler function to the close button. This process is straightforward, and you can refer to the following code to implement it:</p><pre>// Get all the tags inside the parent element add close event<br>[...tagSelectWrap.getElementsByTagName(&#39;span&#39;)].forEach(spanTag =&gt; {<br>    spanTag.getElementsByTagName(&#39;i&#39;)[0].onclick = () =&gt; removeSelectedTag(spanTag);<br>})</pre><p>That’s it!</p><p>Then I add our search components into the task edit view, and refactor our update method as bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgI7UrdPsS0QW3MoEk31Jw.png" /></figure><p>Now if we add an additional task and make updates, you will notice that not only will new tags be added, but the last attached tags will also be attached again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*CPVWL37m5hV6mOFmnr9ohw.png" /></figure><p>One possible solution is to first detach all previously attached tags and then attach them all together. However, another option is to use a helper function called sync which handles the entire process in one step:</p><pre>// option 1:<br>$tags_id = $task-&gt;tags()-&gt;pluck(&#39;id&#39;);<br>$task-&gt;tags()-&gt;detach($tags_id);<br>$task-&gt;tags()-&gt;attach($request-&gt;validated(&#39;tags&#39;));<br><br>// option 2:<br>$task-&gt;tags()-&gt;sync($request-&gt;validated(&#39;tags&#39;));</pre><p>That’s it Let’s see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*TW4YNTVWTIfZSOO9.gif" /></figure><p>We’ve just completed an incredible and extensive article that covers a wide range of topics, including the fascinating realm of many-to-many relationships. In addition, we introduced a brand new model called “tag” and and establish a relationship between user tasks and the associated tags. To enhance the user experience, we even developed blade components specifically designed to manage tags within our forms.</p><p>And again this is the <a href="https://github.com/kazemmdev/laravel101"><strong>repo</strong></a> of our project. Throughout this series of materials, we’ll be taking gradual steps to transform it into a fully functional application.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1504b7008fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Exploring Entity-Model Relationships]]></title>
            <link>https://kazemmdev.medium.com/laravel101-exploring-entity-model-relationships-ad4393cef07f?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad4393cef07f</guid>
            <category><![CDATA[relational-model]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel101]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 03:01:35 GMT</pubDate>
            <atom:updated>2023-08-25T03:59:25.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>Up until now, we’ve built an awesome app that lets users save tasks. But now, we want to take it a step further and save each user’s tasks individually. That means each user will have their own set of tasks. And of course, we’ll make sure to relate the tasks with the current user who’s logged into the app. So, they’ll have easy access to the their tasks. Sounds cool, right?</p><p><strong>Relational Database Management Systems (RDBMS)</strong> are a type of database management system that work based on relationships. Basically, data and relationships are organized using a set of related tables. Many popular DBMSs like <strong>SQLite</strong>, <strong>MySQL</strong>, and <strong>Microsoft Access</strong> follow this structure.</p><p>Now, talking about different types of database management structures is beyond the scope of this article. However, if you’re curious and want to explore more about the various types of DBMS, you can check out the following link:</p><p><a href="https://www.c-sharpcorner.com/UploadFile/65fc13/types-of-database-management-systems/">Types of Databases</a></p><p>Alright, let’s dive into the topic of defining relationships in models.</p><p>When it comes to table relationships, the main ones we encounter are <strong>one-to-many</strong> and <strong>one-to-one</strong>. In a one-to-one relationship, each record in one table is linked to just one record in another table. For instance, think of the connection between a student’s and their account details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*EkpPmXR8XAIVO-Tx.png" /></figure><p>On the other hand, in a <strong>one-to-many</strong> relationship, each record in one table can be associated with multiple records in another table. Take a peek at the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*aAyGmd2EfLTfDhCB.png" /></figure><p>you’ll notice that each customer can have several orders, but each order belongs to only one customer.</p><p>And hey, let’s not forget about another type of relationship called <strong>many-to-many</strong>. To handle this, we convert it into two <strong>one-to-many</strong> relationships using an interface table. Check out the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*1gFc8WlVdUe5GxNS.png" /></figure><p>you’ll see a <strong>many-to-many</strong> relationship between the courses and students tables, which we’ve transformed using an interface table with two one-to-many relationships.</p><p>In our example, each user is associated with their own set of tasks.</p><p>Here’s how it works: a user can have multiple tasks, but each task belongs to only one user. So, to make this happen, we need to update our tasks model migration file and introduce a new attribute called foreignId. This attribute will be responsible for storing connection between a user to the task.</p><p>To establish this connection, we can use any unique data from users table. In our design, we have options like email and ID.</p><p>Here’s a helpful tip: in relational databases, we often use the ID since it optimized retrieval of related models.</p><p>Let’s update our migration file and add foreignId :</p><pre><br>Schema::create(&#39;tasks&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;title&#39;);<br>    $table-&gt;text(&#39;description&#39;)-&gt;nullable();<br>    $table-&gt;foreignId(&#39;user_id&#39;)-&gt;constrained();<br>    $table-&gt;timestamp(&#39;expired_at&#39;)-&gt;nullable();<br>    $table-&gt;timestamps();<br>});</pre><p>As you might have noticed, I’ve used a handy function called constrained here. Its main purpose is to establish a relationship between models in a table. This function adds extra information to attributes, such as the related model’s table name. In this case, the related model is the users table.</p><p>You can actually specify the table name explicitly like constrained(&#39;users&#39;) but this function is smart enough to figure it out automatically based on the foreignId attribute name.</p><p>Now we update our migration file let update our tables:</p><pre>php artisan migrate:fresh --force</pre><p>Well done! Now, let’s talk about how we can actually use this in our project.</p><p>In Laravel, Eloquent provides some handy helper functions to define relationships. In our case, since the task model belongs to a user, we can simply define the belongsTo function in tasks model:</p><pre>class Task extends Model<br>{<br>    public function user()<br>    {<br>        return $this-&gt;belongsTo(User::class);<br>    }<br>}</pre><p>On the other hand, for our user, which can have many tasks, we can use the hasMany function:</p><pre>class User extends Authenticatable<br>{<br>    public function tasks()<br>    {<br>        return $this-&gt;hasMany(Task::class);<br>    }<br>}</pre><p>Of course we doesn’t have many-to-many in our project yet, but let’s talk about this exciting relationship. The good news is that it’s simpler for both models! We only need to use the belongsToMany function for both of them. These functions are usually all we need to define relationships. But if you’re looking for more detailed explanations, you can find them right here:</p><p><a href="https://laravel.com/docs/10.x/eloquent-relationships">Laravel - The PHP Framework For Web Artisans</a></p><p>These functions have some really handy applications. Let’s say we have a task and we want to know the name of the user who created it. In this case, here’s how we can tackle it:</p><pre>$task = Task::find(1);<br>echo $task-&gt;user-&gt;name;</pre><p>Here’s the thing you should know: In our Task model, we’ve got this cool function called “user” defined. Now, you might be wondering why we’re using it as an attribute, without those parentheses.</p><p>Well, let me explain. When we treat these functions as attributes, it’s almost like we’re directly referring to the user model itself using a query. That’s why we can easily access attributes like the user’s name. It’s a convenient way to get the information we need right away!</p><p>Let’s practice it with tasks function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*8fVRfVM5lPNSo7bFMIY8Yw.png" /></figure><p>As you see in above pic you can find all the relevant models for a specific user or perform any query on the task models that are associated with that particular user.</p><p>Now, let’s back to our task controller and update the store function. The goal is to create a new task for the current user and set the user ID attribute. We can achieve this in a very direct way with the following code: (auth()-&gt;id() get current logged in user id):</p><pre>$task = new Task();<br>$task-&gt;title = request(&#39;title&#39;);<br>$task-&gt;descripton = request(&#39;descripton&#39;);<br>$task-&gt;expired_at = request(&#39;expired_at&#39;);<br>$task-&gt;user_id = auth()-&gt;id();<br>$task-&gt;save();</pre><p>However, let me introduce you to an even cooler option using the tasks function. This approach offers some amazing benefits. Check it out:</p><pre>public function store(StoreTaskRequest $request)<br>{<br>    auth()-&gt;user()-&gt;tasks()-&gt;create($request-&gt;validated());<br>    return redirect(&quot;/tasks&quot;, 201);<br>}</pre><p>Here the foreign id of user is handled by tasks</p><p>That’s awesome! Now, let’s update our index function to retrieve all the tasks associated with the currently logged-in user. It’s really simple. Just update the index function like this:</p><pre>public function index()<br>{<br>    return view(&#39;tasks.index&#39;, [&#39;tasks&#39; =&gt; auth()-&gt;user()-&gt;tasks]);<br>}</pre><p>Also we can make use of the auth functions in Blade templates to directly access the tasks of the current user. This means we can remove the task variable passing from the index function. Instead, we can fetch all the tasks within the Blade template itself. It’s super convenient!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEa_7eVxdITpwhCXBKcPhw.png" /></figure><p>In this article, we’ve covered the relationships between users and tasks models in Laravel. The information we discussed is not only important but also highly practical. Mastering complex queries is a key skill for anyone working in the backend. I hope you found this tutorial enjoyable and insightful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad4393cef07f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Exploring Middlewares — Unlocking Multilingual Functionality with Ease]]></title>
            <link>https://kazemmdev.medium.com/laravel101-exploring-middlewares-unlocking-multilingual-functionality-with-ease-183b044a1310?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/183b044a1310</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel101]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 18:50:29 GMT</pubDate>
            <atom:updated>2023-08-17T18:50:29.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Laravel101: Exploring Middlewares — Unlocking Multilingual Functionality with Ease</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>In the previous article, we added user registration functionality to our project. In this article, we will focus on defining access and restrictions for users using middleware in Laravel. Properly defining access is crucial for any website, as we want to control what actions users can perform. For example, as you see in previous article, we don’t want just anyone to be able to add a new task to our site. We can achieve this by using middleware, let’s deep dive into middlewares in Laravel.</p><h3>Middlewares</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCAtquA7d2BcpnDc" /><figcaption>Photo by <a href="https://unsplash.com/@rstar50?utm_source=medium&amp;utm_medium=referral">Roger Starnes Sr</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As the name suggests, <a href="https://laravel.com/docs/10.x/middleware">Middlewares</a> just like pipelines are commands that sit between our request to the server and the server’s response. You might be familiar with the Auth middleware from prior lesson.</p><p>Let’s get back to our project. If you navigate to the app/Http/Middleware directory, you will find some predefined middlewares. For example, one of these middlewares is PreventRequestsDuringMaintenance. When you activate this middleware, users will encounter a 503 error or a message indicating that the service is unavailable usually during you perform updates or maintenance on your service.</p><p>In Laravel, the php artisan down command is used to activate this mode, and php artisan up is used to stop it:</p><p>As you see in following pic when your app is in the maintenance mode then the middleware prevents any requests from being executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vZc9J3Dtpne9Yv53ZYL2Q.png" /></figure><p>Certainly, it is also possible to exclude specific endpoints from the maintenance mode, To do that you need to add your desired endpoint into the except array:</p><pre>class PreventRequestsDuringMaintenance extends Middleware<br>{<br>    /**<br>     * The URIs that should be reachable while maintenance mode is enabled.<br>     *<br>     * @var array&lt;int, string&gt;<br>     */<br>    protected $except = [<br>        //<br>    ];<br>}</pre><p>If you recall from the previous tutorial, you learned that we can add a middleware to an endpoint using the middleware function. Similarly, you can add a middleware to a group of routes using the group function, as shown below.:</p><pre>// one route<br>Route::post(&#39;logout&#39;, LogoutController::class)-&gt;middleware(&#39;auth&#39;);<br><br>// or a group of routes<br>Route::group([&#39;middleware&#39; =&gt; &#39;auth&#39;], function () {<br>    Route::resource(&#39;tasks&#39;, TaskController::class);<br>    Route::post(&#39;logout&#39;, LogoutController::class)-&gt;name(&#39;logout&#39;);<br>});</pre><h4>Create a new Middleware</h4><p>To create a custom middleware, we will use the following artisan command:</p><pre>php artisan make:middleware &lt;NameOfMiddleware&gt;</pre><p>In Laravel, every middleware has a handler function where you can define its logic. This function takes two inputs: the<strong> request </strong>object<strong> </strong>and<strong> </strong>a<strong> closure. </strong>The request object allows you to access the data within the request, while the closure is a function that you can invoke to proceed with the middleware pipelines:</p><pre>public function handle(Request $request, Closure $next)<br>{<br>   return $next($request);<br>}</pre><p>To use this middleware, we need to define it in the kernel.php file located in the Http folder. Let’s take a closer look at the kernel.php file. It contains three arrays, each serving a specific purpose.</p><p>The first array, middleware, is meant for middlewares that are globally applied to all requests.</p><p>The next array, middlewareGroups, is used for applying middlewares to specific group of routes.</p><p>Finally, we have the routeMiddleware array. In this array, middlewares are defined with a key, allowing us to apply a middleware to a specific route. For instance, if you look at the list, you will see auth mentioned, which demonstrates how we can apply it to desired routes.</p><p>Now, let’s try something interesting.</p><h3>Multilingual Laravel Website</h3><p>Sometimes we may need to make our website multilingual, and Laravel provides a convenient tool to facilitate this.</p><p>To set up language resources in Laravel, we first need to run the following command:</p><pre>php artisan lang:publish </pre><p>After running this command, you will notice that in the main directory of your project, there are PHP translation resources that include arrays with keys. These keys represent default terms that can be found in any application. You can add translations to these keys. However, having only an English resource might not be sufficient. Let’s say we want to add French as another language. It can be time-consuming to manually translate all the files and key values into French, especially if you’re not proficient in French.</p><p>Luckily, there is another way! You can add <a href="https://github.com/Laravel-Lang/lang">laravel-lang</a> package to your project that simplifies the process. By running the following command, you can install the package and add French language resources to your lang directory:</p><pre>composer require laravel-lang/common --dev<br><br>php artisan lang:add fr<br>php artisan lang:update</pre><p>Once you have set up the language resources, you can proceed to add translations for specific keys. For example, let’s say we want to add a translation for the key “welcome” in both English and French languages. You can do it like this:</p><pre>&gt;&gt; lang/en.json:<br>&quot;welcome&quot;: &quot;Welcome to Laravel101 tutorials&quot;,<br><br>&gt;&gt; lang/fr.json<br>&quot;welcome&quot;: &quot;Bienvenue dans les tutoriels Laravel101&quot;,</pre><p>You might be wondering how to use it, right? Well, it’s quite simple!</p><p>To utilize it, you just need to use a handy helper function called __(&#39;key&#39;) within your Blade files. For example, if you have a &quot;welcome&quot; key in your language resources, you can display it on the home page of your app like this:</p><pre>@extends(&#39;layouts.app&#39;)<br><br>@section(&#39;title&#39;, &#39;Home Page&#39;)<br><br>@section(&#39;content&#39;)<br>   &lt;div class=&quot;flex flex-center justify-between mb-4&quot;&gt;<br>      &lt;h1 class=&quot;text-xl font-bold &quot;&gt;{{ __(&#39;welcome&#39;) }}&lt;/h1&gt;<br>  &lt;/div&gt;<br>@endsection</pre><p>Additionally, to change the locale of your application to use a specific language, you can modify the locale value inside the config/app.php file of your project. Now set the locale to &#39;fr&#39; and here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gH6QBn-70HRA_Jzrp_rlpg.png" /></figure><p>When it comes to translation, there are a few tips that can come in handy. One useful technique is to use the getLocale function to set the language in an HTML tag, like this:</p><pre>&lt;html lang=&quot;{{ app()-&gt;getLocale() }}&quot;&gt;</pre><p>Another useful feature is the ability to include dynamic values within translations:</p><p>By passing an array of key-value pairs as a second parameter to the helper function, you can specify the keys you want to use for dynamic values. For example:</p><pre>__(&#39;hello&#39;, [&#39;user&#39; =&gt; $username])</pre><p>In the above example, the key &#39;user&#39; is defined for this purpose, allowing you to insert the $username dynamically into the translation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4A223pDXrybhajQ2YavxA.png" /></figure><p>There is also a function called trans_choice that lets you translate selectively based on a given input. It allows you to choose between singular and plural forms of a word. For instance, consider the following example:</p><pre>//  translate file<br>return [<br> &#39;model&#39;  =&gt; &#39;book|books&#39;<br>];<br><br>// in blade:<br>{{ trans_choice(&#39;default.model&#39;,  1 ) }}<br>&gt;&gt;&gt; book <br><br>{{ trans_choice(&#39;default.model&#39;,  2 ) }}<br>&gt;&gt;&gt; books</pre><p>Great! We’ve covered the basics of translation files and the tools Laravel provides for language management. Now, let’s explore how we can dynamically set the language based on user selection using functions and sessions in Laravel.</p><p>Assuming the default language of our site is English, we can configure the language and define the necessary translation keys using helper functions in the config files.</p><p>To handle language selection by the user, we can create a controller called LocaleController and define a store function as follows:</p><pre>use Illuminate\Http\Request;<br><br>class LocaleController extends Controller<br>{<br>    public function __invoke(Request $request)<br>    {<br>        session([&#39;locale&#39; =&gt; $request-&gt;locale]);<br>        return redirect()-&gt;back();<br>    }<br>}</pre><p>To access this function, we define an appropriate route:</p><pre>Route::post(&#39;/locale&#39;, LocaleController::class)-&gt;name(&#39;locale.store&#39;);</pre><p>To display a language selection menu in the navigation blade file, you can add the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pyVvgUsDOLLvRyJft-OMSg.png" /></figure><p>The menu mentioned above allows users to send a request to the server to indicate their desired language. However, there’s still more work to be done. We need to retrieve the selected language from every request on the server, and this can be achieved using a middleware:</p><pre>php artisan make:middleware SwitchLocaleMiddleware</pre><p>Once you’ve executed the command, navigate to the app/Http/Middleware directory and define the middleware as follows:</p><pre>public function handle(Request $request, Closure $next): Response<br>{<br>    if (Session::has(&#39;locale&#39;))<br>        App::setLocale(Session::get(&#39;locale&#39;));<br><br>    return $next($request);<br>}</pre><p>Here we use two object: Session, and App which defined globally and are accessible with session() and app() you can access session from request like $request-&gt;session()</p><p>The App facade is a powerful object that enables us to work with various services within our project. Today, we’ll use it to set the app’s locale.</p><p>The Session provides a convenient and straightforward way to access data specific to the current user’s request. In Laravel, you have multiple options for managing session data, including file, Redis, encrypted cookies, and database. By default, Laravel is configured to use the file session driver, which is suitable for many applications. In our case, we’re using the session to store the user’s locale.</p><p>Now, open the Kernel file located in the app/Http directory and add this middleware to the end of the $middlewareGroups array and in web group because the session driver defined here, like this:</p><pre>protected $middlewareGroups = [<br>  &#39;web&#39; =&gt; [<br>    // Other middleware entries...<br>    \App\Http\Middleware\LanguageMiddleware::class,<br>  ]<br>];</pre><p>That’s it! By following these steps, you’ll have a multilingual site where you can define the translation keys in the respective language folders. The final output will be as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*lKKMZqMJJIoLjm9ZCMYzOg.gif" /></figure><p>That’s fantastic 😍!</p><p>In this tutorial, we explored Laravel Middlewares and discovered how they can be used to enhance our application, particularly in achieving multilingual functionality.</p><p>I hope you found this tutorial helpful, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=183b044a1310" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: A Step-by-Step Guide to Implementing a Simple Authentication System]]></title>
            <link>https://kazemmdev.medium.com/laravel101-manual-authenticate-in-simple-try-3d93146b2de8?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d93146b2de8</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel101]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Mon, 14 Aug 2023 05:28:28 GMT</pubDate>
            <atom:updated>2023-08-14T05:32:58.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>In this tutorial, we will walk you through the process of implementing a robust authentication system manually within your application.</p><p>In the Laravel ecosystem, there are numerous approaches to implementing authentication, ranging from session-based to API-based, and from lightweight packages like <a href="https://laravel.com/docs/10.x/sanctum"><strong>Sanctum</strong></a> to to more complex <a href="https://laravel.com/docs/10.x/passport"><strong>Passport</strong></a>. Additionally, there are handy starter kits such as <a href="https://github.com/laravel/breeze"><strong>Breeze</strong></a> and <a href="https://jetstream.laravel.com/introduction.html"><strong>Jetstream</strong></a>, which provide a streamlined starting point. However, for the purpose of this beginner tutorial, we will focus on implementing a straightforward authentication system that is as simple as possible.</p><p>Let’s begin by registering a user.</p><p>To create our controller in a separate directory, use the following command:</p><pre>php artisan make:controller Auth/RegisterController</pre><p>Inside of this controller we need two function. One function is responsible for displaying the view, while the other handles the controller’s logic.</p><p>Following <strong>REST</strong> architecture, we need a create method to display the registration view and a store method to handle the registration request:</p><pre>class RegisterController extends Controller<br>{<br>    public function create()<br>    {<br>        return view(&#39;auth.register&#39;);<br>    }<br><br>    public function store()<br>    {<br>    }<br>}</pre><p>Then I have developed a simple user form that includes fields for name, email, and password input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r57UTugXBGPe6FCCUSGCUQ.png" /></figure><p>This form has just a simple layout layout.auth without our navbar. Additionally, I have put all the authentication forms into separate directory resources/views/auth</p><p>Now, let’s return to our routes and define the route for user registration.</p><pre>Route::get(&quot;/register&quot;, [RegisterController::class, &#39;create&#39;])-&gt;name(&#39;register&#39;);<br>Route::post(&quot;/register&quot;, [RegisterController::class, &#39;store&#39;])-&gt;name(&#39;register.store&#39;);</pre><p>Next, we need to create a request which could look like bellow:</p><pre><br>class RegisterRequest extends FormRequest<br>{<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; &#39;required|min:3&#39;,<br>            &#39;email&#39; =&gt; &quot;required|email|unique:users,eamil&quot;,<br>            &#39;password&#39; =&gt; &quot;required|min:4|max:20&quot;<br>        ];<br>    }<br>}</pre><p>The email rule is in place to ensure that the email address provided follows the proper email format. The unique rule is used to make sure that the email entered has not been used before.</p><p>No we can simply use it in our store function:</p><pre>public function store(RegisterRequest $request)<br>{<br>    $user = User::create($request-&gt;validated());<br><br>    Auth::login($user);<br><br>    return redirect(&quot;/tasks&quot;);<br>}</pre><p>Here, I make use of an awesome class called Auth to provide a simple login within created user. Additionally, there is another globally defined helper function for Auth like auth(), which you can use: auth()-&gt;login($user)</p><p>Now, let’s have some fun. Go back to the tasks store function and try to retrieve the currently logged-in user in the application. To do this, we can use the dd :</p><pre>Auth::user()<br><br>// or <br>auth()-&gt;user()<br><br>// or <br><br>$request-&gt;user()</pre><p>Here’s how you can do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fSu9Q1rzZjcE8aPSnG8qA.png" /></figure><p>Amazing! This means that our user now logged in in thew application successfully!</p><p>The another thing you need to pay attention here is the mass assignment issue when using the create function for a model (We discussed this issue <a href="https://medium.com/@kazemmdev/laravel101-the-role-of-mass-assignment-in-eloquent-model-54450cc452a4">here</a> ).</p><p>If you look at the User model class created with Laravel, it handles this issue by default:</p><pre>protected $fillable = [<br>    &#39;name&#39;,<br>    &#39;email&#39;,<br>    &#39;password&#39;,<br>];<br><br>protected $hidden = [<br>    &#39;password&#39;,<br>    &#39;remember_token&#39;,<br>];<br><br>protected $casts = [<br>    &#39;email_verified_at&#39; =&gt; &#39;datetime&#39;,<br>    &#39;password&#39; =&gt; &#39;hashed&#39;,<br>];</pre><p>As you can see in the code, the password is converted to a hash by casting. This is a secure and useful way to store passwords in the database.</p><p>Now, What if you want to use your own hash method in a different way? Well, you can do it inside our request class. Just before passing the data, remember that all the processes occur after validation, and it just happens by rewriting validated method:</p><pre>namespace App\Http\Requests;<br><br>use Illuminate\Foundation\Http\FormRequest;<br>use Illuminate\Support\Facades\Hash;<br><br>class RegisterRequest extends FormRequest<br>{<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;name&#39; =&gt; &quot;required|min:3&quot;,<br>            &#39;email&#39; =&gt; &quot;required|email|unique:users,eamil&quot;,<br>            &#39;password&#39; =&gt; &quot;required|min:4|max:20&quot;<br>        ];<br>    }<br><br>    public function validated($key = null, $default = null)<br>    {<br>        return array_merge($this-&gt;validator-&gt;validated(), [<br>            &#39;password&#39; =&gt; Hash::make(request(&#39;password&#39;))<br>        ]);<br>    }<br>}</pre><p>The Laravel Hash facade offers secure hashing using Bcrypt and Argon2 algorithms. For detailed instructions you can refer to the official Laravel <a href="https://laravel.com/docs/10.x/hashing">documentation</a>.</p><p>Now, let’s return to our registry controller and bring everything together:</p><pre>namespace App\Http\Controllers\Auth;<br><br>use App\Http\Controllers\Controller;<br>use App\Http\Requests\RegisterRequest;<br>use App\Models\User;<br><br>class RegisterController extends Controller<br>{<br>    public function create()<br>    {<br>        return view(&#39;auth.register&#39;);<br>    }<br><br>    public function store(RegisterRequest $request)<br>    {<br>        $user = User::create($request-&gt;validated());<br><br>        auth()-&gt;login($user);<br><br>        return redirect(&quot;/tasks&quot;);<br>    }<br>}</pre><p>It’s really clear, but in the real world, after a user is created, we typically send a verification email to the user. However, for now, let’s keep things simple and cover that in the next lessons. Okay, now let’s get started by moving on to the login controller:</p><pre>php artisan make:controller Auth/LoginController</pre><p>Then let’s add routes :</p><pre>Route::get(&#39;login&#39;, [LoginController::class, &#39;create&#39;])-&gt;name(&#39;login&#39;);<br>Route::post(&#39;login&#39;, [LoginController::class, &#39;store&#39;])-&gt;name(&#39;login.store&#39;);</pre><p>Just like in the register controller, we need to create a function in the login controller to display our login view, which I’ve kept simple from register form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsGOwbJKESWR3v7ENYhq3Q.png" /></figure><p>And here is our LoginRequest</p><pre>class LoginRequest extends FormRequest<br>{<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;email&#39; =&gt; &#39;required|email&#39;,<br>            &#39;password&#39; =&gt; &#39;required&#39;<br>        ];<br>    }<br>}</pre><p>Finally let’s back to our login controller.</p><p>When it comes to creating a login system there are a few steps we need to follow. First, we check if the user exists in our database. Then, we verify if the entered password matches the hashed password stored in our records. If everything checks out and the user exists, we generate a session for them and grant access to the application.</p><p>You can handle all of the scenario by yourself, use another helper function called attempt in auth facade that takes care of all these tasks. It’s quite simple to use. We just need to pass the user’s credentials and it handles the rest:</p><pre>class LoginController extends Controller<br>{<br>    public function create()<br>    {<br>        return view(&#39;auth.login&#39;);<br>    }<br><br>    public function store(LoginRequest $request)<br>    {<br>        if (auth()-&gt;attempt($request-&gt;validated())) {<br>            return redirect()-&gt;intended(&#39;/tasks&#39;);<br>        }<br><br>        return back();<br>    }<br>}</pre><p>You can simply use the above code but if you want to handle exceptions and display error messages, you can make use of the helper function called withErrors. Just modify the code as follow:</p><pre>public function store(LoginRequest $request)<br>{<br>    if (auth()-&gt;attempt($request-&gt;validated())) {<br>        return redirect()-&gt;intended(&#39;/tasks&#39;);<br>    }<br><br>    return back()<br>        -&gt;withErrors([<br>            &#39;email&#39; =&gt; &#39;The provided credentials do not match our records.&#39;,<br>        ]);<br>}</pre><p>Sure! If you’d like to go back to the view with the email value pre-filled, you can use the withInput function. Here&#39;s how you can do it:</p><pre>return back()<br>    -&gt;withInput($request-&gt;only(&#39;email&#39;))<br>    -&gt;withErrors([<br>        &#39;email&#39; =&gt; &#39;The provided credentials do not match our records.&#39;,<br>    ]);</pre><p>And this is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7VkE-r-hcNPF48XyTAn8Q.png" /></figure><p>Well, our next task is to finalize the authentication process and focus on implementing the logout feature. To begin, we’ll create a controller:</p><pre>php artisan make:controller Auth/LogoutController</pre><p>And ensure its routes are properly defined:</p><pre>Route::post(&#39;logout&#39;, LogoutController::class)-&gt;name(&#39;logout&#39;);</pre><p>Since we have only one function in controller, I suggest utilizing an invocable method:</p><pre>namespace App\Http\Controllers\Auth;<br><br>use App\Http\Controllers\Controller;<br><br>class LogoutController extends Controller<br>{<br>    public function __invoke()<br>    {<br>        auth()-&gt;logout();<br><br>        return redirect(&#39;/login&#39;);<br>    }<br>}</pre><p>That’s really easy! Now, let’s create our logout view. It’s a simple form with a button that you can click to submit the logout request:</p><pre>&lt;form method=&quot;POST&quot; action={{ route(&#39;logout&#39;) }}&gt;<br>    @csrf<br>    &lt;button type=&quot;submit&quot;&gt;Logout&lt;/button&gt;<br>&lt;/form&gt;</pre><p>How can we use this view in our application? and when should we avoid using it?</p><p>Currently, the navbar just displays options for signing in and signing up. We need to display a logout view when the user is logged in and this these options when the user is unauthorized.</p><p>To achieve this, we have two functions in blade. The first one auth is used to display content exclusively for authenticated users, while the second one guest is specifically for guest users or users who haven’t been authorized yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7HicPmfkqtzieF2FTHuQw.png" /></figure><p>That’s it!</p><p>One important point is that we don’t want guests to have access to the task resources. Additionally, we want the logout request to be accessible only to authorized users.</p><p>In the upcoming lessons, we will explore <strong>middleware</strong> in Laravel in detail. But for now, let’s briefly mention that it consists of rules that check the current request before it reaches the intended endpoint. In our case, we check if the current request is made by an authorized user, and if not, we want to return a 403 exception.</p><p>To implement this, we can use the auth middleware. Laravel provides a function to add middleware specifically to a route. Here’s an example:</p><pre>Route::post(&#39;logout&#39;, LogoutController::class)-&gt;middleware(&#39;auth&#39;);</pre><p>Additionally, we can group multiple routes together and apply the same middleware to all of them. Here’s an example:</p><pre>Route::group([&#39;middleware&#39; =&gt; &#39;auth&#39;], function () {<br>    // Add your protected routes here<br>});</pre><p>Now, let’s move on to our web routes and add both the logout and tasks resources to a group:</p><pre>Route::group([&#39;middleware&#39; =&gt; &#39;auth&#39;], function () {<br>    Route::resource(&#39;tasks&#39;, TaskController::class);<br>    Route::post(&#39;logout&#39;, LogoutController::class)-&gt;name(&#39;logout&#39;);<br>});</pre><p>Great job! We have successfully implemented the authorization system in Laravel, and it was really straightforward and clear. While we can add many more features to it, let’s keep it simple for now.</p><p>You can find out the project code of this series tutorial in the <a href="https://github.com/kazemmdev/laravel101">repo</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d93146b2de8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: The Role of Mass Assignment in Eloquent Model]]></title>
            <link>https://kazemmdev.medium.com/laravel101-the-role-of-mass-assignment-in-eloquent-model-54450cc452a4?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/54450cc452a4</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel101]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 16:49:46 GMT</pubDate>
            <atom:updated>2023-08-10T16:49:46.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>Clean and readable code is an important aspect that distinguishes experienced programmers from beginners. Achieving this level of code quality requires experience and observation. While each framework has its own set of rules, I’ll focus on sharing some helpful principles within the context of the Laravel framework in this training course.</p><p>In our previous article, we discussed the REST Architecture which with its template enhance our code readability inside our controllers. Now, let’s explore the concept of mass assignment and the a tool called Request.</p><p>Before we begin, let’s take a moment to understand the output of the validate function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PP4vDLFERgaEqNbx1qqXnw.png" /></figure><p>An essential aspect to understand about the validate function is that it exclusively returns an array of data that conforms to the rules you have specified. In other words, even if a user attempts to send an injected field to our server, the validate function will only return the information that we have defined! This helps to maintain the integrity and security of our server-side data processing:</p><pre>$data = request()-&gt;validate([<br>    &#39;title&#39; =&gt; &#39;required|min:3|max:120|unique:tasks,title&#39;,<br>    &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>    &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>]);<br><br>Task::create($data);</pre><p>See? It’s much more readable now. Let’s proceed and make a request to see the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsb_a0jfFMBEOI0t1qRG7A.png" /></figure><p>The reason for the error you encountered is that models in Laravel, by default, prevent mass assignment to avoid accepting incorrect values. For example, if you haven’t properly defined the validation rules, sensitive user information like email or password could be set incorrectly. Laravel wants to ensure you’re aware of this potential issue. Luckily, we have two solutions to change this default behavior.</p><p>One solution is to use the fillable property, which is an array of fields that you want to allow for mass assignment</p><pre>protected $fillable = [&#39;attribute&#39;];</pre><p>Alternatively, you can use the guarded property, which works the opposite way by allowing you to specify the fields you don&#39;t want to be mass assignable:</p><pre>protected $guarded = [&#39;attribute&#39;];</pre><p>In our example, we need to include one of these properties in our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVJ_vbT5wQ9ysghsoOrk5g.png" /></figure><p>I personally prefer to use an empty array of guarded</p><p>Now, let’s explore another useful tool within Laravel called <strong>FormRequest</strong>, which allows us to separate request validation from our controller. This separation enhances code clarity and organization.</p><p>By creating a Request class, we can define the validation rules specific to that request, keeping our controller focused on handling the business logic.</p><p>To create a Request class, we can use the following artisan command:</p><pre>php artisan make:request &lt;request-name&gt;</pre><p>Additionally, Laravel provides convenient options when using the make:model artisan command.</p><p>For example, you can include the -c option to generate a new controller for the model, the -r option to indicate that the generated controller should be a resource controller, the -m option to create a new migration file for the model, and the -R option to create new form request classes and automatically use them in the resource controller:</p><pre>php artisan make:model &lt;model-name&gt; -c -r -m -R</pre><p>Well, let’s back to our project add a request for our store function:</p><pre>php artisan make:request StoreTaskRequest</pre><p>Once created, you can open the StoreTaskRequest file inside directory app/Http/Requests and define your validation rules inside the rules method:</p><p>(Hint: I just drop unique rule for title to make it more sense! )</p><pre>class StoreTaskRequest extends FormRequest<br>{<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;title&#39; =&gt; &#39;required|min:3|max:120&#39;,<br>            &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>            &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>        ];<br>    }<br>}</pre><p>By default, there is an authorize function too that you can decide if an user is authorized to make this request, right? for now just set its value true to let anyone has access to do request.</p><p>In addition to the rules, you can also customize the error messages by overriding the messages method in your FormRequest file:</p><pre>public function messages(): array<br>{<br>    return [<br>        &#39;title.required&#39; =&gt; &#39;Hey, don\&#39;t forget to fill in your title!&#39;,<br>        &#39;title.min&#39; =&gt; &#39;Oops! Your name should be at least three characters long.&#39;,<br>        &#39;description.min&#39; =&gt; &#39;Hold up! The description too short!!!&#39;,<br>    ];<br>}</pre><p>Now let’s use it!</p><p>To achieve that, we can inject the StoreTaskRequest class into the store method of our controller. This allows Laravel to handle the validation process automatically. If the validation fails, the user will be redirected back to the previous page, along with the error messages. On the other hand, if the validation passes successfully, the controller method will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6DrmOthBvdvU6uO84iDTg.png" /></figure><p>In the picture above, to obtain validated data, you can use the validated method. If you don&#39;t specify any keys as input for the validated function, it will return all the keys defined in the rules array. Alternatively, if you only want specific keys or an array of desired ones, you can simply pass them as input to the function. It&#39;s straightforward, right?</p><p>Now Let’s make the UpdateTaskRequest for update function:</p><pre>php artisan make:request UpdateTaskRequest</pre><p>And update UpdateTaskRequest as follow:</p><pre><br>class UpdateTaskRequest extends FormRequest<br>{<br>    public function authorize(): bool<br>    {<br>        return true;<br>    }<br><br>    public function rules(): array<br>    {<br>        return [<br>            &#39;title&#39; =&gt; &#39;required|min:3|max:120&#39;,<br>            &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>            &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>        ];<br>    }<br>}</pre><p>Again to use that we only need to we can easily include the UpdateTaskRequest class as a parameter in the update method of our controller, But this time we have to apply the update method on binding model, as shown below:</p><pre>public function update(Task $task, UpdateTaskRequest $request)<br>{<br>    $task-&gt;update($request-&gt;validated());<br>    return redirect(&quot;/tasks&quot;);<br>}</pre><p>And that brings us to the end of this article. We’ve covered how to refactor our code and improve its clarity. In the next article, we’ll dive into authorization within Laravel. I hope you found this article enjoyable and informative. Stay tuned for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54450cc452a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Implement RESTful Architecture in Controllers]]></title>
            <link>https://kazemmdev.medium.com/laravel101-implement-restful-architecture-in-controllers-30b31f9e3aa4?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/30b31f9e3aa4</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel101]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 15:42:51 GMT</pubDate>
            <atom:updated>2023-08-13T04:44:42.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>In our project, we have made progress in developing our task model and evaluating the submitted information. The purpose of this article and the upcoming ones is to introduce Restful architecture into our project. By the end of this tutorial, you will learn a programming pattern that not only improves code readability and cleanliness but also makes programming more interesting. believe me!</p><p><strong>Restful</strong> architecture, short for <strong>Representational State Transfer</strong>, enhances code readability, as its name suggests. In Laravel, there is a predefined template that we will use to modify the existing code. First, let’s examine the table below, taken from the Laravel <a href="https://laravel.com/docs/master/controllers#actions-handled-by-resource-controller">documentation</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*sbrv0YdAM_iW5W0tnz-Wbw.png" /></figure><p>The table categorizes the main characteristics of HTTP requests sent to the server into four types: <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong>, and <strong>DELETE</strong>. <strong>GET</strong> is used to retrieve information, <strong>POST</strong> is used to save records, <strong>PUT</strong> is used to update records, and <strong>DELETE</strong> is used to delete records. In Laravel, the names of paths and functions are defined accordingly. Therefore, by simply looking at a defined path, you can easily understand the corresponding function in the controller and its purpose.</p><p>Now, let’s proceed and implement these principles step by step in our existing code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGjtGVKFfU0LCB8P45Ns3A.png" /></figure><p>I just simply define the function I don’t do anything inside newly added ones.</p><p>Then let’s back to routes and modify all tasks routes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAn5qxDUdfMcmpk9Z5JlVQ.png" /></figure><p>I decide to move tasks page into new page an let home page a simple landing page for our project!</p><p>Now, let’s define each page and all the necessary components that we need to implement, page by page. Here I just add other blank blade pages for the rest of them! and the new routes which we will go through all of them in this article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QDuEZfz6WdNx0XyLRoVVw.png" /></figure><p>Let’s start with index page where we want list all tasks. The first thing is we have to change it view name inside TaskController from home to tasks.index and then transfer all content inside home into new directory tasks/index.blade.php :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqHyIV0xBLfHZQgVMB9XuQ.png" /></figure><p>That’s it!</p><p>Creating the function is also a simple task. We just need to define a view function and point it to tasks/create.blade.php. I did this and tried to open the page, but it threw an exception indicating that we need to change the route name used in the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZerLg6ob6BowvMnGA_elA.png" /></figure><p>Well, this is where RESTful design comes to our rescue. When you adhere to this design principle, you will know how to name the routes for each page. This way, you can avoid the inconvenience of encountering errors like the one we just experienced.</p><p>Now let’s try to store new task and see it works or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mw8suXkCqnCqdIy5W5QNVg.png" /></figure><p>What? If you look at form you will see that the route is correct but the request is not found for post request. Please pay attention to the action part of the form.</p><p>Currently, we are on a different page, specifically <a href="http://localhost:8000/songs/create">http://localhost:8000/tasks/create</a>. Therefore, when defining the action in the form, we need to start the path from the root, rather than starting from tasks, simply means we need to use “/” at the beginning or you can use route helper function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0P19K2uZhwEJVAN4IW3eQ.png" /></figure><p>The error has been fixed, it’s as simple as that… But here’s the thing: after creating a new task, we want to be redirected back to the tasks page. To achieve this, we used back which isn’t my option I like to use the redirect function instead! with this function we can define what exactly the redirect page have be!</p><p>You may have noticed that I made a change to the error section to improve its functionality and ensure that all errors received from the backend are displayed. The simple modification I made was to utilize the all() function, which get the errors object data as an array. This allows us to easily access and display all the error messages.</p><p>Now, let’s move on to the task show page. Since we’ve already implemented the route, we only need to follow two steps here. First, we navigate to the controller and define the show function to handle the request. Finally, we manage the display of information using Blade.</p><p>Let’s look to show route:</p><pre>Route::get(&#39;/tasks/{task}&#39;, [TaskController::class, &#39;show&#39;])-&gt;name(&#39;tasks.show&#39;);</pre><p>The key difference here is the dynamic path. Let’s take a closer look at the variable we’re sending to the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q19GMTA5Lv7vCcAX1l4NHA.png" /></figure><p>By sending any value to the server, we can retrieve it within the `show` function and display the appropriate output. Let’s complete the function and give it a try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajedMRnq9TW863hldKeYqA.png" /></figure><p>I just made a simple show page!</p><p>Everything seems to be working correctly, but what if we enter an incorrect ID? In such case, the user would encounter a server exception. It’s important to handle this scenario by displaying a 404 error page, indicating that the requested item doesn’t exist. Thankfully, Laravel provides solutions for this using Eloquent:</p><pre>// findOrFail<br>$task = Task::findOrFail($id);<br><br>// or firstOrFail<br>$task = Task::where(&#39;id&#39;, $id)-&gt;firstOrFail();</pre><p>These two approaches work fine, but let’s use Laravel’s built-in binding, as it’s simpler.</p><p>By specifying the variable type we receive as input in the `show` function, Laravel automatically recognizes it and performs a process called binding to find the corresponding record for us. Moreover, if it doesn’t find a record through the model, it will return the same 404 error:</p><pre>public function show(Task $task)<br>{<br>    return view(&#39;tasks.show&#39;, compact(&#39;task&#39;));<br>}</pre><p>It’s as simple as that!</p><p>Great! Now, we have only two things left: editing and deleting a task.</p><p>To edit a task, first we need to load the data of the record we want to edit and populate a form, similar to the task creation form, with the initial data, so our edit function is look like this:</p><pre>public function edit(Task $task)<br>{<br>    return view(&#39;tasks.edit&#39;, compact(&#39;task&#39;));<br>}</pre><p>Now, let’s just copy creation form into edit page. The first change we need to make is to use the passed data in our input fields. However, we want to ensure that if the update request fails and the form is returned with errors, the previously entered values are filled in the input fields. To handle this, we can utilize the old() method. Here&#39;s an example for the input field representing the task title:</p><pre>&lt;input ... value=&quot;{{ old(&quot;title&quot;) ?? $task-&gt;title }}&quot; /&gt;</pre><p>This code checks if there is any previously entered value (old(&quot;title&quot;)) and if not, it falls back to the original task title value ($task-&gt;title).</p><p>Additionally, we need to update the route for the edit form, you have to update it also:</p><pre>&lt;form method=&quot;POST&quot; action={{ &#39;/tasks/&#39; . $task-&gt;id }} &gt; ...</pre><p>Or just use route helper function which provides a cleaner and more readable approach. In this case, you can specify the route name tasks.update as the first parameter and pass the task ID as the second parameter:</p><pre>&lt;form method=&quot;POST&quot; action={{ route(&#39;tasks.update&#39;, $task-&gt;id) }} &gt; ...</pre><p>The final step is to change the request type to PUT/PATCH for the edit form. However, within HTML forms, we can only use the POST or GET methods. To overcome this limitation, Blade provides a helpful function called @method :</p><pre>&lt;form method=&quot;POST&quot; action={{ route(&#39;tasks.update&#39;, $task-&gt;id) }}&gt;<br>    @method(&#39;PUT&#39;)<br>    &lt;!-- Rest of the form --&gt;<br>&lt;/form&gt;</pre><p>By including @method(&#39;PUT&#39;) within the form, Blade will generate a hidden input field that overrides the form method and sets it to PUT. This way, when the form is submitted, it will be treated as a PUT request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4KKsXtR_v81ZoYjVlyBdw.png" /></figure><p>Finally the delete action, as before we need to update destroy function as bellow and use another eloquent helper function called delete :</p><pre>public function destroy(Task $task)<br>{<br>    $task-&gt;delete();<br>    return redirect(&quot;/tasks&quot;);<br>}</pre><p>But how and where we should call this action!</p><p>To overcome this one we could add another simple form inside task.index and like edit page define delete method inside the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bokf8hnmefLIK5mLrPDS1g.png" /></figure><p>Great job! You’ve successfully implemented all the necessary features to work with models in Laravel while following the RESTful structure. As you can see, the code has become much shorter and easier to read. Pretty impressive, huh?</p><p>Now, let’s look at routes/web.php again. Imagine having a massive project with dozens of models. Writing duplicate path functions for each model can be long list. But don’t worry! Laravel has a solution for this.</p><pre>Route::resource(&#39;tasks&#39;, TaskController::class);</pre><p>By using this method, we actually define paths that are equivalent to all the paths we defined earlier in one go. It saves you from the hassle of writing repetitive code for every single model.</p><p>It’s also important to note that resource automatically generates all the <strong>RESTful</strong> functions by default. in most cases like you won’t require all of these functions.</p><p>To address this, Laravel provides a helpful method called only that allows you to selectively include only the desired functions.</p><pre>Route::resource(&#39;tasks&#39;, TaskController::class)-&gt;only([&#39;create&#39;, &#39;store&#39;]);</pre><p>There is another function that works exactly the opposite of this function called except which can exclude any unnecessary functions.</p><pre>Route::resource(&#39;tasks&#39;, TaskController::class)-&gt;except(&#39;delete&#39;);</pre><p>It’s super useful!</p><p>Laravel artisan command offers some nifty options that can make your life even easier when generating controllers. For example, with a simple command, you can create all the necessary functions we discussed earlier in the controller, right from the start:</p><pre>php artisan make:controller TestController -r -m Task</pre><p>This -r option here say to artisan to create my controller by implementing restful scheme and That -m is just to assign its model which here is task</p><p>I hope you found this tutorial enjoyable and informative. You’ve done an excellent job so far! If you have any more questions or need further assistance, feel free to ask. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30b31f9e3aa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Validate your Application’s Incoming Data]]></title>
            <link>https://kazemmdev.medium.com/laravel101-validate-your-applications-incoming-data-323c52707bc0?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/323c52707bc0</guid>
            <category><![CDATA[laravel101]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 15:26:09 GMT</pubDate>
            <atom:updated>2023-08-07T15:26:09.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>In the previous article, we learned how to send information to the server and save tasks in a table. However, what if the user sends wrong information or leaves the tasks title field empty? I told you! In such cases, we will encounter the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S27t26c_PrctZ5O-bxnvfw.png" /></figure><p>To solve this problem, we need to ensure that the requested data is correct before adding a new record. We can evaluate the information entered using Laravel’s validate property in the request helper function.</p><h4>Request Validation</h4><p>To do this, let’s go back to the store function in the controller and define a set of rules to evaluate the entered information.</p><p>The first rule is to check if the Task title is required, so that the user cannot send an empty name.</p><pre>public function store()<br>{<br>    request()-&gt;validate([<br>        &#39;title&#39; =&gt; &#39;required&#39;<br>    ]);<br><br>    $task = new Task();<br>    $task-&gt;title = request(&#39;title&#39;);<br>    $task-&gt;save();<br>    return back();<br>}</pre><p>Now, if we leave the title field empty and send a request, we will see that the previous error page is not displayed, and only the page is refreshed. However, if we want to display the error related to the user’s request and maintain the user interface of the program, we need to display the errors variable. The errors variable contains JSON data, and when our request is rejected during the evaluation stage, it will return the relevant error message for us.</p><p>To display the error message from the evaluation stage, we need to make some changes to the blade file related to our create task. By doing so, when we send a request with an empty field, we will see the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oA5J5C_MTrFvJLeFgsfLpA.png" /></figure><p>Let’s add some additional rules, such as a character limit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAVxB-w0gNGfkQ1kEQuEyA.png" /></figure><p>Or ensuring that the Task title is not repeated (although this is usually used for usernames or internal site addresses, here we are using it for educational purposes):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHUn3lhClobiaxn2xLIoyg.png" /></figure><p>You can also consider other conditions for the entered information, the list of which can be found at the laravel official doc <a href="https://laravel.com/docs/master/validation#available-validation-rules"><strong>here</strong></a><strong>.</strong></p><p>Another thing you may have noticed is that when the user encounters an error in their request, the field gets cleared. To prevent this, there is a useful helper function called old that allows you to return the value previously entered by the user. Let’s add this to our form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQKiBtLq4Wq0RbrV9mv4_A.png" /></figure><p>Now, Let’s add another attribute to our task model which is tasks description, which let users time more about a task but this attribute definitely isn’t required and we want to user add it as an optional data.</p><p>To do that first we need to add another mitigation to our project to add another column into task table!</p><blockquote>Please remember this important tip when working on a project that is still in development and not yet released. It’s crucial to keep the migrations simple and avoid creating too many separate migration files. Having numerous migrations can make it difficult to track and understand the data model attributes. when it comes to adding changes to a live, production-ready application, it’s necessary to create a new migration. Since, it’s crucial to avoid accidentally resetting any existing data.</blockquote><p>But here, only for learning purposes I add another migration:</p><pre>php artisan make:migration add_description_to_tasks_table</pre><p>As you see in following up and down function I just add one column into our tasks table:</p><pre>/**<br> * Run the migrations.<br> */<br>public function up(): void<br>{<br>    Schema::table(&#39;tasks&#39;, function (Blueprint $table) {<br>        $table-&gt;text(&#39;description&#39;)-&gt;after(&#39;title&#39;)-&gt;nullable();<br>    });<br>}<br><br>/**<br> * Reverse the migrations.<br> */<br>public function down(): void<br>{<br>    Schema::table(&#39;tasks&#39;, function (Blueprint $table) {<br>        $table-&gt;dropColumn(&#39;description&#39;);<br>    });<br>}</pre><p>As you noticed you can use after method to specify the exact position where you want to add the column. Additionally, you can use the nullable attribute to allow the column to contain null values. Although you can also set a default value by default method for the column, but it recommended using nullable as it’s more optimized for query speed. However, please note that there are cases, such as with boolean columns, where using nullable may not be feasible or appropriate.</p><p>Now let’s run it and check the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gdDVTEGAnJbt3wV5x1lFog.png" /></figure><p>Everything works fine but the description is not right after!</p><p>While Laravel provides convenient methods for working with databases, there are limitations with certain methods, especially when using SQLite. Unfortunately, SQLite does not support inserting a column at a specific position in a table. So, even if you use the after method in Laravel, the column will not be placed immediately after the specified column as expected. This is a limitation of SQLite itself, and it&#39;s not something that can be directly addressed through Laravel methods.</p><p><strong><em>Fortunately, this limitation only applies to SQLite databases. If you’re using PostgreSQL or MySQL, you won’t encounter this</em></strong></p><p>To fix this, We can remove last migration and as just change tasks migration files. We can reset all tables with:</p><pre>php artisan migrate:reset</pre><p>But suppose that we have some data we won’t to reset them, so the solution here is rollback all migration files!</p><p>To rollback last migration you can use following command:</p><pre>php artisan migrate:rollback </pre><p>And to rollback certain amount of migrations:</p><pre>php artisan migrate:rollback --step=&lt;steps_count&gt;</pre><p>I just remove last migration file and do our changes in tasks migration file, you’ll see after running php artisan migrate command our desired changes will be added!</p><p>I add some rule for description and as you can see in following pic everything works fine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zcqjCazaYLusK598W24Xkg.png" /></figure><p>That was super simple? huh!</p><p>Now let’s add another field? what about due to date and time? To do that let’s add another time column called expired_at which is also nullable</p><pre>Schema::create(&#39;tasks&#39;, function (Blueprint $table) {<br>    $table-&gt;id();<br>    $table-&gt;string(&#39;title&#39;);<br>    $table-&gt;text(&#39;description&#39;)-&gt;nullable();<br>    $table-&gt;timestamp(&#39;expired_at&#39;)-&gt;nullable();<br>    $table-&gt;timestamps();<br>});</pre><p>That’s it let’s migrate tasks table again:</p><pre>php artisan migrate:rollback<br>php artisan migrate</pre><p>Then We have to update store function as bellow:</p><pre>public function store()<br>{<br>    request()-&gt;validate([<br>        &#39;title&#39; =&gt; &#39;required|min:3|max:120|unique:tasks,title&#39;,<br>        &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>        &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>    ]);<br><br>    $task = new Task();<br>    $task-&gt;title = request(&#39;title&#39;);<br>    $task-&gt;description = request(&#39;description&#39;);<br>    $task-&gt;expired_at = new \DateTime(request(&#39;expired_at&#39;));<br>    $task-&gt;save();<br><br>    return redirect(&quot;/&quot;);<br>}</pre><p>There are a few important points to consider. Firstly, when you need to validate a date in Laravel, you can use the built-in date validation rules. Let’s review them below:</p><p>date: This validation rule checks if a given input is a valid date:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date&#39;</pre><p>date_format: This rule validates if the input matches a specific date format:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date_format:Y-m-d&#39;,</pre><p>after:date: This rule ensures that the input date is after a specified date:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date|after:2023–01–01&#39;, // or maybe tommorow</pre><p>after_or_equal:date: This rule validates if the input date is equal to or after a specified date:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date|after_or_equal:2023–01–01&#39;,</pre><p>before:date: This rule ensures that the input date is before a specified date:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date|before:2023–01–01&#39;,</pre><p>before_or_equal:date: This rule validates if the input date is equal to or before a specified date:</p><pre>&#39;date_field&#39; =&gt; &#39;required|date|before_or_equal:2023–01–01&#39;,</pre><p>By utilizing these date format validation rules, you can ensure that the input dates meet your specified criteria within your Laravel application.</p><p>The second point to note is <strong>casting expired_at</strong> data as the exact datetime PHP data type. Sometimes, Laravel doesn&#39;t automatically recognize the data type, even if we validate it. to resolve it we can use Datetime helper class. or casting inside the data model! How?!</p><p>When we created our Task model, we actually created an Eloquent model, which is an amazing feature in Laravel. However, so far, we haven&#39;t made any modifications to it. By default, every Eloquent model we create is stored in the app/models directory of our Laravel project (note that this location may vary in older versions). To cast the data in our model, we need to make some changes by adding a rule to the casts variable, like this:</p><pre>protected $casts = [<br>    &#39;expired_at&#39;  =&gt; &#39;datetime&#39;<br>];</pre><p>By this defining we don’t need to use Datetime class anymore:</p><pre>public function store()<br>{<br>    request()-&gt;validate([<br>        &#39;title&#39; =&gt; &#39;required|min:3|max:120|unique:tasks,title&#39;,<br>        &#39;description&#39; =&gt; &#39;nullable|min:3|max:255&#39;,<br>        &#39;expired_at&#39; =&gt; &#39;nullable|date|after:now&#39;<br>    ]);<br><br>    $task = new Task();<br>    $task-&gt;title = request(&#39;title&#39;);<br>    $task-&gt;description = request(&#39;description&#39;);<br>    $task-&gt;expired_at = request(&#39;expired_at&#39;);<br>    $task-&gt;save();<br><br>    return redirect(&quot;/&quot;);<br>}</pre><p>Please note that you don’t need to casting for the created_at and updated_at columns, as Laravel handles them by default. However, in general, <strong>it&#39;s considered a best practice to explicitly define all the data model&#39;s fields and cast them accordingly:</strong></p><pre>protected $casts = [<br>    &#39;title&#39;       =&gt; &#39;string&#39;,<br>    &#39;description&#39; =&gt; &#39;string&#39;,<br>    &#39;created_at&#39;  =&gt; &#39;datetime&#39;,<br>    &#39;updated_at&#39;  =&gt; &#39;datetime&#39;,<br>    &#39;expired_at&#39;  =&gt; &#39;datetime&#39;<br>];</pre><p>This approach ensures that you have a clear understanding of each model&#39;s attributes and their respective data types. Just keep in mind that in real-world projects, it can sometimes be challenging to determine all the fields of a data model by solely relying on migrations.</p><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLfHWBYoqf3g4lyxqflW1g.png" /></figure><p>Again every time you need to walk through project you can find out <a href="https://github.com/kazemmdev/laravel101">here</a>!</p><p>That’ it! I hope you found this tutorial enjoyable!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=323c52707bc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel101: Create and Submit a Form to the Server]]></title>
            <link>https://kazemmdev.medium.com/laravel101-create-and-submit-a-form-to-the-server-d49e94a1d85f?source=rss-1528838ac4fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49e94a1d85f</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel101]]></category>
            <dc:creator><![CDATA[Kazem Mirzaei]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 15:52:05 GMT</pubDate>
            <atom:updated>2023-08-03T15:52:05.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wfPYLyfQgycdMSh8uomfcA.png" /></figure><p>In the previous tutorial, we learned how to connect a SQLite database to our Laravel application. We created a table using migration and saved a record in the tasks table using the tinker. Now, let’s create a simple form to save a new record in the database.</p><p>To begin, we’ll add a basic form to inside another page. I just need a simple form as follow:</p><pre>&lt;form&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;title&quot;&gt;<br>   &lt;button type=&quot;submit&quot;&gt;save&lt;/button&gt;<br>&lt;/form&gt;</pre><p>Please note that this form doesn’t currently send any data on its own. To make the form submit its information when the button is pressed, we need to add two attributes to the form tag. First, we specify the request method we want to use, which in this case is POST. Second, we provide the server route where we want to handle the form submission. Let’s update the code as follows:</p><pre>&lt;form method=&quot;POST&quot; action=&quot;tasks&quot;&gt;<br>   &lt;input type=&quot;text&quot; id=&quot;title&quot;&gt;<br>   &lt;button type=&quot;submit&quot;&gt;save&lt;/button&gt;<br>&lt;/form&gt;</pre><p>I add just add some styles and here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfs0a2eE9aSWj_SiRj645A.png" /></figure><p>If we try to submit the form now, we’ll encounter an error indicating that there is no route defined to handle this request, which is expected. To fix this, let’s go to the web.php file and define a new route for handling POST requests:</p><pre>Route::get(&#39;/&#39;, [TaskController::class, &#39;index&#39;])-&gt;name(&#39;tasks.all&#39;);<br><br>Route::view(&#39;/new-task&#39;, &#39;tasks.new&#39;);<br><br>Route::post(&#39;/tasks&#39;, [TaskController::class, &#39;store&#39;])-&gt;name(&#39;tasks.create&#39;);</pre><p>Now, let’s define the store function inside the controller to handle the form submission. The question is, how do we retrieve the data sent by the form?</p><p>Laravel provides a helper function called request that allows us to access the submitted data.</p><p>To verify if the process is working correctly, we can use another commonly helper function called dd (short for &quot;Dump and Die&quot;). This function will display the input it receives in the browser and stop the program execution at that point.</p><p>By using the dd function, we can inspect the submitted data and ensure that everything is functioning as expected. Let’s see the above output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_McWtG1DPUeDPe1Us4hAvg.png" /></figure><p>What just happened? What? 🤯🤯</p><p>The error occurred because of a security feature in Laravel called <strong>CSRF</strong> (cross-site request forgery) protection. This feature is designed to prevent <strong>CSRF</strong> attacks. I’ll explain more about this feature, known as middleware, later on. For now, all you need to know is that Laravel checks for a token in every POST request sent to the server to prevent <strong>CSRF</strong> attacks. If the token is not present or invalid, the request is rejected.</p><p>To address this issue, you can simply add @csrf to your form. When you refresh the page, Laravel automatically adds a hidden input tag to your form containing the necessary token. This code is specifically generated by Laravel for this form.</p><p>Now, if you enter some text in the form and click the “add” button again, the server will validate your request and display the text in the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*LXCewOI2_MSCXS_4JoJseg.png" /></figure><h4>Fix Page Expired in Iframe (optional)</h4><p>This particular part of the tutorial might be a bit confusing and seems to be slightly outside the main focus of the series. However, if you’ve noticed, in the previous tutorials, I utilized a simple browser within VSCode. You can install any browser extension or set it up from <a href="https://dev.to/equiman/vscode-browser-inside-2b06"><strong>here</strong></a>. But here’s the catch: most of these browsers display our webpage inside an iframe, essentially embedding our site.</p><p>To address this, in the context of development, you need to inform Laravel that for testing purposes, you can set the “same_site” attribute of sessions to “none” inside config/sessions and set “SESSION_SECURE_COOKIE” to “true” in the .env file. This will allow Laravel to ignore the embeding situation. However, please be aware that this setup in production enables others to embed your site’s pages on their own websites, which can pose a security risk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F5_gj7vpqACqH6eku8Zog.png" /></figure><p>As you can see in the image above, I am able to make a POST request with this configuration</p><p>Also I have included my VSCode settings within the project repo. with this setting you can easily open it up in inside browser by simply pressing the Alt+Shift+Backspace shortcut. You don’t need to install any additional packages in your VSCode!</p><p>Let’s complete the store function.</p><p>In the previous tutorial, we used Tinker to save a record. We’ll do the same here and save the task submitted through the form into the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--2xoXRM9a5CYmQulMPw9A.png" /></figure><p>Congratulations! In this tutorial you just learn how to send successfully secure request with CSRF protection to the server and saved a record in the database based on that request. In the next tutorial, we’ll cover how to validate user input before storing it in the database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49e94a1d85f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>