<?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 Brice Hartmann on Medium]]></title>
        <description><![CDATA[Stories by Brice Hartmann on Medium]]></description>
        <link>https://medium.com/@brice_hartmann?source=rss-6fd5158e5434------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kDsVrUQs4DX8mCPFeHqejA.jpeg</url>
            <title>Stories by Brice Hartmann on Medium</title>
            <link>https://medium.com/@brice_hartmann?source=rss-6fd5158e5434------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 12:10:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brice_hartmann/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[Parallel Claude Code Sessions with LaborForest]]></title>
            <link>https://medium.com/@brice_hartmann/parallel-claude-code-sessions-with-laborforest-51f6df7fb7fc?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/51f6df7fb7fc</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 02:22:47 GMT</pubDate>
            <atom:updated>2026-08-22T02:23:27.955Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was originally posted on </em><a href="https://brice.codes/posts/parallel-claude-code-sessions-with-laborforest"><em>brice.codes</em></a><em>.</em></p><h3>Overview</h3><p>If you’ve worked with Claude Code for a while, you’ve probably seen this message in your terminal:</p><blockquote>Tip: Use git worktrees to run multiple Claude sessions in parallel.</blockquote><p>If you’re already using worktrees to run multiple Claude sessions in parallel, great. You’re already familiar with the concepts LaborForest builds upon.</p><p>If you’re new to git worktrees, below is a surface-level overview:</p><ul><li>Git worktrees allow multiple branches of the same repository to be checked out in different directories simultaneously. The same branch cannot be checked out in multiple worktrees at the same time</li><li>Git worktrees do not require cloning the same repository more than once. You can switch contexts and work on different things in parallel without affecting other branches</li><li>Git worktrees have been built into Git since 2015, but AI coding agents are greatly popularizing their adoption</li></ul><h4>Git worktrees in practice</h4><p>In practice, a development workflow can look something like this:</p><ol><li>Create a new branch or check out an existing branch for the feature or bug fix you’re working on</li><li>Plan your changes and kick off implementation using Claude Code</li><li>While Claude Code works, create a new git worktree, on a new or existing branch, for another initiative</li><li>In the new worktree’s directory, plan your changes and kick off implementation using Claude Code</li><li>Repeat steps 3 and 4 as much as you’d like</li><li>When changes on a branch within a worktree are complete: commit and push the changes; open a pull request and remove the worktree</li></ol><p>This allows you to switch between multiple Claude Code sessions on different branches within the same project, at the same time.</p><p>No more stashing changes to check behavior on another branch and no more abandoning current progress to tackle something more urgent.</p><h4>Pain points</h4><p>This works great in theory, but there’s a part I glossed over above:</p><p><em>What if your repository requires some setup for the local development environment?</em></p><p>For some projects, this can just be a few commands you need to run per new worktree. For other projects, this can be a tedious sequence of steps, time that adds up and takes away from developer velocity.</p><p>Yes, you can write setup scripts for each project to address this. However, unless you have significant control over each repository, standardization can be difficult. You can easily end up with a collection of brittle bash spaghetti.</p><p>Take, for example, a Laravel project using Herd Pro for services. For each new worktree, you may need to:</p><ol><li>create an environment file from the example in the project</li><li>update the environment file variables for just this worktree (to maintain isolation)</li><li>create a local S3-compatible bucket for storage using MinIO</li><li>create a new MySQL schema</li><li>install composer dependencies</li><li>install NPM dependencies</li><li>build front-end assets</li><li>link and secure the site in Laravel Herd</li><li>seed the new database with test data</li></ol><p>Then of course, when you are done with a worktree, you should tear down these resources too.</p><h3>Introducing LaborForest</h3><p><a href="https://github.com/bricehartmann/labor-forest/">LaborForest</a> is a completely free and open source desktop app for macOS to manage git worktrees and local action workflows.</p><p>With LaborForest, all the steps above can become a few clicks. You can easily spin up or tear down local development environments, coupled to git worktrees, and visually keep track of your worktrees and development state of each.</p><h3>LaborForest in action</h3><p>The below gif is a demonstration of using LaborForest for a local Laravel project.</p><p>The steps taken are:</p><ol><li>Create a new workspace for a new branch feature/example, using main as the base branch</li><li>Set up a local development environment for the new workspace (LaborForest term for the combination of a worktree and branch)</li><li>Observe the sequence of steps executing in realtime via a UI loosely inspired by GitHub Actions</li><li>Open a browser using the new environment’s APP_URL to confirm the local site loads successfully</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S6bFE8d5fmm_Hc9cYrQQog.gif" /><figcaption>LaborForest in action</figcaption></figure><h3>An example with Laravel</h3><p>Let’s dive into what was required to record the above gif.</p><h4>Project assumptions</h4><p>The demonstration above was with a newly generated Laravel project, configured to match my preferences and setup with Herd.</p><ul><li>SESSION_DRIVER set to redis</li><li>QUEUE_CONNECTION set to redis</li><li>REDIS_PREFIX set to example-laravel-database-</li><li>AWS_BUCKET set to example-laravel</li><li>AWS_ACCESS_KEY_ID set to herd</li><li>AWS_SECRET_ACCESS_KEY set to secretkey</li><li>AWS_URL set to <a href="http://localhost:9000/labor-forest-example-laravel">http://localhost:9000/example-laravel</a></li><li>AWS_ENDPOINT set to <a href="http://localhost:9000/">http://localhost:9000</a></li></ul><p>These settings are not prerequisites for using LaborForest. You are free to customize your configuration and workflows as needed for your project.</p><h4>Example workflows</h4><p>Upon loading a project in LaborForest, a new directory is created at the root of your project: .laborforest. It is up to you if you&#39;d like to commit this directory or ignore it by adding the path to .git/info/exclude.</p><p>Workflows are .yaml files placed in the .laborforest/workflows directory within your project. Each .yaml file describes:</p><ul><li>The status the workspace must be in to allow running the workflow (suspended, ready, or null)</li><li>The status the workspace will be in upon successful execution of the entire workflow (suspended or ready)</li><li>Where in the list of workflows this specific workflow should appear (sort order)</li><li>The list of steps the workflow executes when run</li></ul><p><strong>Workflows: </strong><strong>up, </strong><strong>refresh, and </strong><strong>down</strong></p><p>The example workflows for a Laravel project, shipped with LaborForest, are below. You are not limited to using these three workflows. You can have as many custom workflows in LaborForest as you’d like.</p><p>up.yaml is the workflow used when spinning up a new local development environment for a new workspace</p><ul><li>copies the .env file from the primary project directory (if workspace is not the primary workspace)</li><li>updates the .env file with workspace-specific configuration, for isolation (if workspace is not the primary workspace)</li><li>creates a local S3 bucket (if it doesn’t already exist)</li><li>creates the MySQL schema (if it doesn’t already exist)</li><li>installs composer dependencies</li><li>installs NPM dependencies</li><li>builds front-end assets</li><li>links and secures the Laravel Herd site</li><li>runs the refresh workflow below</li></ul><p><em>.laborforest/workflows/up.yaml</em></p><pre>resource_type: workflow<br>require_status: suspended<br>ending_status: ready<br>sort_order: 0<br>steps:<br>  - name: &#39;Copy .env file from primary project directory&#39;<br>    type: shell<br>    if: &#39;test &quot;{{ WORKSPACE_DIR }}&quot; != &quot;{{ PROJECT_PRIMARY_DIR }}&quot;&#39;<br>    run: &#39;cp &quot;{{ PROJECT_PRIMARY_DIR }}/.env&quot; .env&#39;<br>  - name: &#39;Update .env file&#39;<br>    type: update_env<br>    if: &#39;test &quot;{{ WORKSPACE_DIR }}&quot; != &quot;{{ PROJECT_PRIMARY_DIR }}&quot;&#39;<br>    map:<br>      APP_URL: &#39;https://{{ WORKSPACE_SLUG_KEBAB }}.test&#39;<br>      AWS_BUCKET: &#39;{{ WORKSPACE_SLUG_KEBAB }}&#39;<br>      DB_DATABASE: &#39;{{ WORKSPACE_SLUG_SNAKE }}&#39;<br>      REDIS_PREFIX: &#39;{{ WORKSPACE_SLUG_KEBAB }}-database-&#39;<br>  - name: &#39;Create S3 bucket&#39;<br>    type: shell<br>    unless: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api head-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    run: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api create-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    env:<br>      AWS_ACCESS_KEY_ID: &#39;{{ ENV_AWS_ACCESS_KEY_ID }}&#39;<br>      AWS_SECRET_ACCESS_KEY: &#39;{{ ENV_AWS_SECRET_ACCESS_KEY }}&#39;<br>      AWS_DEFAULT_REGION: &#39;{{ ENV_AWS_DEFAULT_REGION }}&#39;<br>  - name: &#39;Create MySQL schema&#39;<br>    type: shell<br>    run: &#39;mysql -h {{ ENV_DB_HOST }} -P {{ ENV_DB_PORT }} -u {{ ENV_DB_USERNAME }} $([[ -z &quot;{{ ENV_DB_PASSWORD }}&quot; ]] &amp;&amp; echo &quot;--skip-password&quot; || echo &quot;-p{{ ENV_DB_PASSWORD }}&quot;) -e &quot;CREATE DATABASE IF NOT EXISTS {{ ENV_DB_DATABASE }} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci&quot;&#39;<br>  - name: &#39;Install Composer dependencies&#39;<br>    type: shell<br>    run: &#39;composer install -v --ansi --no-interaction&#39;<br>  - name: &#39;Install NPM dependencies&#39;<br>    type: shell<br>    run: &#39;npm ci&#39;<br>  - name: &#39;Build assets&#39;<br>    type: shell<br>    run: &#39;npm run build&#39;<br>  - name: &#39;Link Laravel Herd site&#39;<br>    type: shell<br>    run: &#39;herd link --no-interaction --secure {{ WORKSPACE_SLUG_KEBAB }}&#39;<br>  - name: &#39;Refresh application data&#39;<br>    type: workflow<br>    run: refresh</pre><p>refresh.yaml is the workflow used to reset a local development environment for an existing workspace</p><ul><li>runs fresh migrations</li><li>empties the local S3 bucket</li><li>clears the default queue</li><li>wipes the Laravel log file</li><li>runs the database seeder</li></ul><p><em>.laborforest/workflows/refresh.yaml</em></p><pre>resource_type: workflow<br>require_status: ready<br>ending_status: ready<br>sort_order: 1<br>steps:<br>  - name: &#39;Run fresh migrations&#39;<br>    type: shell<br>    run: &#39;php artisan -vvv migrate:fresh&#39;<br>  - name: &#39;Empty S3 bucket&#39;<br>    type: shell<br>    if: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api head-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    run: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3 rm s3://{{ ENV_AWS_BUCKET }} --recursive --include=&quot;*&quot;&#39;<br>    env:<br>      AWS_ACCESS_KEY_ID: &#39;{{ ENV_AWS_ACCESS_KEY_ID }}&#39;<br>      AWS_SECRET_ACCESS_KEY: &#39;{{ ENV_AWS_SECRET_ACCESS_KEY }}&#39;<br>      AWS_DEFAULT_REGION: &#39;{{ ENV_AWS_DEFAULT_REGION }}&#39;<br>  - name: &#39;Clear the default queue&#39;<br>    type: shell<br>    run: &#39;php artisan queue:clear&#39;<br>  - name: &#39;Wipe logs&#39;<br>    type: shell<br>    run: &#39;truncate -s 0 storage/logs/laravel.log&#39;<br>  - name: &#39;Run database seeder&#39;<br>    type: shell<br>    run: &#39;php artisan -vvv db:seed&#39;</pre><p>down.yaml is the workflow used to tear down a local development environment for a workspace</p><ul><li>empties the local S3 bucket (prerequisite for deleting it)</li><li>deletes the local S3 bucket</li><li>drops the MySQL schema</li><li>removes the Laravel Herd site</li></ul><p><em>.laborforest/workflows/down.yaml</em></p><pre>resource_type: workflow<br>require_status: ready<br>ending_status: suspended<br>sort_order: 100<br>steps:<br>  - name: &#39;Empty S3 bucket&#39;<br>    type: shell<br>    if: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api head-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    run: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3 rm s3://{{ ENV_AWS_BUCKET }} --recursive --include=&quot;*&quot;&#39;<br>    env:<br>      AWS_ACCESS_KEY_ID: &#39;{{ ENV_AWS_ACCESS_KEY_ID }}&#39;<br>      AWS_SECRET_ACCESS_KEY: &#39;{{ ENV_AWS_SECRET_ACCESS_KEY }}&#39;<br>      AWS_DEFAULT_REGION: &#39;{{ ENV_AWS_DEFAULT_REGION }}&#39;<br>  - name: &#39;Delete S3 bucket&#39;<br>    type: shell<br>    if: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api head-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    run: &#39;aws --endpoint={{ ENV_AWS_ENDPOINT }} s3api delete-bucket --bucket {{ ENV_AWS_BUCKET }}&#39;<br>    env:<br>      AWS_ACCESS_KEY_ID: &#39;{{ ENV_AWS_ACCESS_KEY_ID }}&#39;<br>      AWS_SECRET_ACCESS_KEY: &#39;{{ ENV_AWS_SECRET_ACCESS_KEY }}&#39;<br>      AWS_DEFAULT_REGION: &#39;{{ ENV_AWS_DEFAULT_REGION }}&#39;<br>  - name: &#39;Drop MySQL schema&#39;<br>    type: shell<br>    run: &#39;mysql -h {{ ENV_DB_HOST }} -P {{ ENV_DB_PORT }} -u {{ ENV_DB_USERNAME }} $([[ -z &quot;{{ ENV_DB_PASSWORD }}&quot; ]] &amp;&amp; echo &quot;--skip-password&quot; || echo &quot;-p{{ ENV_DB_PASSWORD }}&quot;) -e &quot;DROP DATABASE IF EXISTS {{ ENV_DB_DATABASE }}&quot;&#39;<br>  - name: &#39;Remove Laravel Herd site&#39;<br>    type: shell<br>    run: &#39;herd unlink --no-interaction {{ WORKSPACE_SLUG_KEBAB }}&#39;</pre><h4>Claude Code in parallel</h4><p>With these workflows in place, we can now easily manage our local development environments per workspace.</p><p>In a few clicks, we can:</p><ul><li>create a new workspace</li><li>spin up the local development environment for the new workspace</li><li>launch our favorite IDE or Terminal with a working directory of the workspace</li></ul><p>This allows us to use Claude Code on different copies of the same project in tandem. While waiting for Claude Code to finish responding to one prompt, you can be prompting in another isolated environment for the same project.</p><h3>Letting Claude Code drive LaborForest</h3><p>Notice that the loop above still has you in it. You create the workspace, you click up, you launch the IDE, and only then does Claude Code get to work.</p><p>LaborForest can expose itself to AI agents over the <a href="https://modelcontextprotocol.io/">Model Context Protocol</a>, so the agent performs those actions instead.</p><h3>Connecting Claude Code</h3><p>The MCP server is off by default, and read only by default when you first switch it on. Both toggles live on the Settings screen, along with the port it listens on, which defaults to 9189.</p><p>With MCP enabled, the Settings screen shows an Add to Claude Code field. That one line is the entire registration — click it to copy, then run it:</p><pre>claude mcp add --transport http laborforest --scope user http://127.0.0.1:9189/mcp/laborforest --header &quot;Authorization: Bearer &lt;token&gt;&quot;</pre><p>Any client that speaks HTTP MCP connects to the same URL. The command carries the server’s bearer token, so treat it like any other credential.</p><h4>What the agent sees</h4><p>The server publishes 14 tools, 6 resources and 3 prompts.</p><p>The resources are read-only JSON, and they’re how the agent orients itself:</p><ul><li>projects and project — every repository you&#39;ve registered, and one of them by UUID</li><li>workspaces — every workspace of a project, each with its path, branch, status and git_status</li><li>template-variables — the mustache tags a command or workflow step accepts</li><li>workflow-schema — the grammar of a workflow file</li><li>settings — your global configuration</li></ul><p>The tools are the actions you’d otherwise click: find-project-by-path, add-project, add-workspace, add-workspace-example-workflows, run-workflow, validate-workflow, override-workspace-status, purge-workflow-logs, remove-project, the three launch-* tools, and the two that write configuration.</p><p>The prompts are author-workflow, convert-setup-to-workflow and diagnose-workflow-run.</p><p>The full reference for every tool, resource and prompt is in the <a href="https://github.com/bricehartmann/labor-forest/blob/main/docs/mcp.md">MCP documentation</a>.</p><h4>In practice</h4><p><strong>Start work on a ticket.</strong> One prompt replaces the whole opening sequence of this article: add-workspace creates the worktree and branch, run-workflow runs your up workflow, and launch-ide puts the result on screen. If the project has no workflows yet, add-workspace-example-workflows seeds the bare, javascript or laravel starter set first.</p><p><strong>See what’s already running.</strong> The workspaces resource hands back every workspace&#39;s branch, status and whether its working tree is clean, in a single read. That&#39;s the parallel-sessions picture from the top of this article, except the agent can see it too.</p><p><strong>Tear down when a branch merges. </strong>The agent reads workspaces, runs your down workflow against the ones that are finished, and calls remove-project when a whole repository is no longer wanted. Its remove_directory and remove_worktrees arguments mean it can also just deregister a project and leave everything on disk.</p><p><strong>Write the workflows themselves.</strong> Remember the brittle bash spaghetti from earlier? convert-setup-to-workflow reads what your project already documents — a README section, a Makefile, package scripts, a compose file — and splits it into the up, down and operational workflows that reproduce it. author-workflow writes a single one from a description of what it should do.</p><p>No tool writes a workflow file. The agent reads the workflow-schema resource, writes the YAML with its own file tools, and checks it with validate-workflow until it passes. Neither prompt runs the workflow to test it — starting a run stays your decision.</p><p><strong>Heal a failed run.</strong> When a workflow fails, the workspace is left in error, and nothing runs while it sits there. diagnose-workflow-run sends the agent to the run logs in .laborforest/ignored/logs/, where the failing step is the one with a non-zero exitCode and every step after it is marked aborted. The agent fixes the cause, confirms the fix with validate-workflow, calls override-workspace-status to put the workspace back to ready or suspended, and runs the workflow again, without you touching the app.</p><p>A workspace whose run is still in flight can’t be overridden, so an agent can’t yank a status out from underneath a job that’s still writing to it.</p><h4>What it won’t do</h4><p>The server binds to 127.0.0.1 only. Every request needs the bearer token, the Host and Origin headers have to name the loopback interface, and there&#39;s a rate limit of 120 requests a minute.</p><p>Read only is the default, and it’s strict: in that mode the server publishes exactly two tools, find-project-by-path and validate-workflow. Everything else is withheld from the tool list entirely, rather than published and then refused.</p><p>Turn read only off and a workflow step is arbitrary shell running under your own account. That’s why run-workflow is annotated destructive, along with remove-project, purge-workflow-logs and the two configuration tools — a client that asks you to approve destructive calls will ask about those. The three launch tools deliberately carry no annotation at all: nothing in LaborForest changes, but they do run a command you configured.</p><p>Finally, run-workflow queues the run and returns a log ID immediately. It never returns step output, so you still watch the run in the app — which, if you&#39;ve read this far, is the part worth watching anyway.</p><h3>Conclusion</h3><p>LaborForest is free and entirely open source. You can build from source, or grab the latest release binary for your Mac’s architecture on the <a href="https://github.com/bricehartmann/labor-forest/releases">releases page</a>.</p><h4>Read the Docs</h4><p>I encourage you to <a href="https://github.com/bricehartmann/labor-forest/tree/main#documentation">read the documentation</a> included in the LaborForest repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51f6df7fb7fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing a static site’s content with Notion]]></title>
            <link>https://medium.com/@brice_hartmann/managing-a-static-sites-content-with-notion-473a1ba25439?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/473a1ba25439</guid>
            <category><![CDATA[notion]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 20:35:18 GMT</pubDate>
            <atom:updated>2026-03-06T20:35:18.597Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was originally posted on </em><a href="https://brice.codes/posts/managing-a-static-sites-content-with-notion.html"><em>brice.codes</em></a><em>.</em></p><p>This post dives into the development journey that resulted in the website <a href="https://tuli.space/">tuli.space</a>.</p><h3>Background</h3><p>My partner, Tuli, is an incredible Chicago-based movement artist, educator, producer, and choreographer. Tuli has made a significant impact within the dance community in Chicago. However, SquareSpace had grown to be frustrating and was no longer meeting the needs of this career.</p><p>Like many software engineers, hearing about an outstanding problem I felt I could address with code (and coffee) made my brain twitch. Being stuck on an unwieldy and restrictive website builder simply wouldn’t do. With Tuli’s blessing, we dove in and started planning.</p><h3>Initial requirements</h3><p>After a healthy amount of brain-fueled exercises (brain-picking, brain-storming, brain-dumping…) we landed on a relatively simple set of initial goals and requirements:</p><ul><li>A website to house information about Tuli’s career: ongoing involvements, previous work, upcoming events, etc</li><li>This website must be simple, mobile responsive, quick to update, and not take months to build</li><li>Hosting and tooling for this project should be relatively cheap (or at least cheaper than SquareSpace)</li><li>A contact form is needed, with protection against spam and bots</li><li>Basic analytics must be available</li></ul><h3>First thing’s first</h3><p>The initial approach was simple enough. I’d use the marvelous static site generator <a href="https://hydephp.com/">HydePHP</a>, which is built on top of <a href="https://laravel-zero.com/">Laravel Zero</a>.</p><p>Any client-side interactivity could be accomplished with <a href="https://alpinejs.dev/">Alpine.js</a>, a lightweight JavaScript framework.</p><p>Cheap(ish) hosting would be on AWS. Specifically: an S3 bucket configured to host a static site with a CloudFront distribution in front of it (for both SSL and caching), a Lambda function to serverlessly process contact form submissions (validating a reCAPTCHA verification, persisting submissions in DynamoDB, and notifying Tuli via an email sent by SES). AWS resources would be managed via CloudFormation templates.</p><p>The front end of the contact form would use <a href="https://developers.google.com/recaptcha">Google’s reCAPTCHA</a> for protection against automated submissions.</p><p>Deployments would be as simple as pushing up changes and letting a GitHub Actions workflow handle generating the static site’s files, syncing them to S3, and creating a cache invalidation in CloudFront.</p><p>I’ve worked with each of these technologies before, so the learning curve would be relatively shallow. So far so good.</p><h3>Code code code</h3><p>So, filled with aspiration and armed with a terminal, I broke ground. The initial project generation and organization was easy enough; HydePHP has an amazing convention-based approach to managing pages, posts, media, and more. After some back and forth about colors, styling, and layout, we finally settled on project theming that was Good Enough. I am a man of many digital talents; visual design is not one of them.</p><h3>Copy and assets</h3><p>The original plan was based on the assumption that content and images would not need to be updated frequently. Tuli could just make an update in our shared Notion page, leave a comment notifying me of the desired changes, and throw something at me if I was taking too long to start manually inputting the changes. I was hard-coding content in the Blade templates, which worked well for most things. Images were simply downloaded, converted to a .webp format with the cwebp CLI tool, and committed directly to the repository.</p><h3>List/detail pages</h3><p>Here’s where things started to get interesting: out-of-the-box HydePHP generates an HTML file per Markdown file or Blade template. This was great for the surface-level pages, but what about pages that followed a list/detail pattern? Was I really willing to copy/paste Blade templates, all having the same structure, and just manually update the content and image source(s) dozens of times? No, I was not.</p><p>So what’s a humble developer to do when a framework doesn’t behave the way a project needs? Well, <em>read the source</em> of course! A really cool thing about HydePHP is that it’s both open source and extensible. I dug into how pages are generated and stumbled across the DataCollection class. As the beginning of the source&#39;s docblock states, the class:</p><blockquote><em>Automatically generates Laravel Collections from static data files</em></blockquote><p>That sounds perfect for this use case. I had a collection of data and I wanted a reasonable way to manage and programmatically interact with it.</p><h3>Extending HydePHP</h3><p>I knew from reading the docs (which you should always do) that HydePHP was designed to be extensible. After a little more digging I found the HydeExtension abstract class which (again from the beginning of the docblock) states:</p><blockquote><em>When creating a HydePHP extension, you should create a class that extends this one</em></blockquote><p>Sounds straightforward enough! I created a directory for my “models” (YAML files), extended the DataCollection class to point to it, and extended the HydeExtension class. I also created a class I named ModelContainer, responsible for holding all parsed models in memory (as an Illuminate Collection), which I bound to the service container as a singleton. More on this later. In my HydePHP extension class, I implemented discoverFiles and discoverPages methods which parses the YAML files and registers the page(s) for each model (another class I created, ModelPage, that extends HydePHP&#39;s HydePage class).</p><h3>A page out of Eloquent’s book</h3><p>Now that I had a way to load all models into a collection, I figured it would be nice to be able to interact with the data in a way similar to which I’m accustomed (<a href="https://laravel.com/docs/12.x/eloquent">Eloquent</a>). So of course I built out an ORM-esque set of functionality.</p><p>To start, I needed a base (abstract) class from which all of my model classes would inherit. The constructor of my base model class would accept an associative array (or FrontMatter class instance, which is included with HydePHP). I overrode the PHP magic __get method and used some reflection wizardry to implement ways to access attributes in an object-oriented way. I also implemented a way for the child classes to specify &quot;casts&quot; (just for string-backed enums and Carbon instances), some basic relationships, and instances of the Markdown class (also shipped with HydePHP). In my YAML files, I referenced the names of files containing markdown, allowing me to write things like event descriptions and personal biographies in markdown instead of including it in the YAML files themselves.</p><p>Each YAML file uses a unique string (“slug”) as an identifier (instead of incrementing integers).</p><h3>Relationships in YAML</h3><p>For relationships, I wanted a way to denote when models are related to each other. Events belong to Venues (and Venues have many Events). People (educators) belong to many Events and vice versa. I implemented some simple classes named BelongsTo, HasMany, and BelongsToMany. These relationship classes are responsible for resolving an instance (or collection of instances) of related model(s), based upon the relationship method defined on the model class.</p><p>BelongsTo and HasMany relationships were easy: simply resolve models based upon a Fully Qualified Class Name and an identifier. For BelongsToMany, however, I needed the equivalent of a pivot table. To solve this problem, I ended up with an approach that stores pivot data in an additional YAML file; one file per BelongsToMany relationship. This file contains a simple list of foreign identifier pairs with each item in the list representing a relationship.</p><h3>Collections for scopes</h3><p>There was one piece of the ORM puzzle missing for my use case, however: scopes. I wanted a way to filter a collection of models using a fluent syntax, similar to Eloquent scopes applied to a query builder. To accomplish this I extended Illuminate’s Collection class, once per type of model, and defined my &quot;scopes&quot; to be methods that return a filtered collection.</p><p>With attributes, casts, markdown file references, relationships, and scopes, I now had everything I needed to work with data stored in YAML files using my makeshift Object-Relational Mapping feature. The result is being able to programmatically interact with models.</p><h3>Putting together progress</h3><p>This is all great, but without a way to display the data to the website’s visitors, it isn’t more much than an implementation exercise. So next, I created classes that extend the aforementioned ModelPage class. These classes defined: an output directory for the final pages, the name of a Blade template, the FQCN of the relevant model, and methods for the page&#39;s title and description.</p><h3>Metadata and Open Graph</h3><p>The methods for the page’s title and description are used to add meta tags to the head of the resulting HTML page. These methods are easily accessible as HydePHP makes the page instance available in the Blade template as the $page variable. There was a key piece missing, however: Open Graph images. Links to pages within this website would surely be shared on social media, so of course we need a unique Open Graph image for each page.</p><p>Remember that part earlier in this article where I mentioned HydePHP is built on top of Laravel Zero? This makes the framework extremely powerful and ripe for customization. I won’t go into much detail here, but in summary I implemented a custom command to loop through each defined page and generate an Open Graph image using <a href="https://image.intervention.io/v3">Intervention Image</a>. You can read more about how I’ve done <a href="https://brice.codes/posts/generating-open-graph-images-for-each-post-in-hyde.html">something similar for this blog here</a>.</p><p>Now I could reference image file names in my YAML model definitions, run a command, and end up with generated images for each page. Naturally, this processes ended up as part of the GitHub Actions deployment workflow, but more on that soon.</p><h3>Enter CloudFormation</h3><p>Of course, this project needed infrastructure. I created CloudFormation templates for:</p><ul><li>the static site itself (S3 + CloudFront distribution)</li><li>the contact form (Lambda + DynamoDB + SES)</li><li>a proxy for Plausible.io (CloudFront with Lambda@Edge)</li></ul><p>The static site template and contact form are pretty routine. The proxy, however, took a bit of tinkering. I wanted to proxy <a href="https://plausible.io/">Plausible.io</a>’s analytics script because it’s not uncommon for adblockers to block this script (even though Plausible anonymizes most of the data). There are two parts to this: serving the initial JavaScript when a request is made to a subdomain of tuli.space at /js/script.js, and proxying requests made to /api/event to Plausible&#39;s API.</p><h3>Putting theory into practice</h3><p>With all of the above, plus a quick and dirty GitHub Actions workflow, I was ready to deploy the first version of the website. All that was remaining was the data, stored in .yml and .md files (and images).</p><p>Very, very quickly, Tuli and I realized how tedious of a process collecting all the data would be, communicating the content to me, and me putting it into files that could be committed to the repository. There must be a more efficient way.</p><h3>Notion to the rescue</h3><p>All of our communication about what needed to change was happening in Notion. Wait a minute, I thought, Notion has an API! I created four databases in Notion, which would become the source of truth for all website resources: people, events, venues, and blog posts. With the help of Claude Code, I again created some custom commands.</p><p>This time, the commands were responsible for querying for data via Notion’s API and writing it in predetermined formats to YAML files. Markdown content came from the Notion database item’s page itself, which was transformed from rich text. Images were downloaded separately, converted to .webp (if not already done), and placed in the _media directory. I also created a sync:all command, which invokes all other sync commands.</p><p>Now, all I had to do each time Tuli needed to make an update to a detail page’s resource, was run a command, commit, and push to GitHub. The GitHub actions workflow took care of the rest.</p><h3>Tentative success</h3><p>At this point I was feeling pretty accomplished. The combination of HydePHP and Notion had been successfully frankensteined into an improvised CMS. There was only one problem remaining: I still had to personally run commands from my laptop every time Tuli made a change. Close, but no cigar.</p><p>I theorized about how I could transfer my command-invoking powers to Tuli. Briefly, I considered setting up the project on Tuli’s laptop and creating a shortcut of some kind to do the deed. This didn’t feel quite right because updating the site was still tied to <em>a</em> laptop, even if it wasn’t <em>my</em> laptop.</p><h3>Simple button</h3><p>As a general rule when working with technology, I like to imagine what I (or a client) <em>wants</em> without considering what is <em>technically feasible</em>. Then, I work backwards a trim scope into something that can be accomplish. What did I want in this case? A simple button. All I wanted was a button somewhere Tuli could click that would kick off the entire process. Is that too much to ask?</p><h3>Remaining pieces</h3><p>Lots of hidden requirements revealed themselves once I pulled on the threads of my desired button. If I spun up a simple static site with a single button, I’d still need to protect the site with some form of authorization. Furthermore, once this theoretical button was clicked, there still needed to be somewhere the actual sync command was run. Not to mention a way for the result to be committed to source control.</p><p>It turned out the answer was already staring me in the face: Notion and GitHub Actions. Notion supports firing a webhook as the result of a button click, and GitHub Actions supports triggering workflows via API calls. Unfortunately, as of writing this article, Notion’s outgoing webhooks do not support including a body for the request. This is an issue because GitHub’s API requires specifying the branch in a JSON payload when triggering a workflow.</p><h3>One more CloudFormation template</h3><p>First I tried using <a href="https://zapier.com/">Zapier</a>, which worked. However, it only worked on a paid plan due to tier limitations (I was on the free trial). I couldn’t justify paying for Zapier, forever, for a single button. Instead, I reached for AWS Lambda. Using API Gateway to sit in front of a Lambda function for invocation used to be a requirement for something like this, but in 2022, AWS introduced <a href="https://aws.amazon.com/blogs/aws/announcing-aws-lambda-function-urls-built-in-https-endpoints-for-single-function-microservices/">Lambda Function URLs</a>.</p><p>This means all I had to do was create a Lambda function that, among verifying the request used a valid secret, triggered a workflow in GitHub Actions. This workflow was responsible for running the sync:all command, opening a Pull Request with the resulting files, and merging it. Upon merge, a secondary workflow kicked off to deploy (as a commit was just pushed to main, after all). One more CloudFormation template later, I was ready for my simple button.</p><h3>Status update</h3><p>As soon as I tested the button in Notion, another problem made itself painfully obvious: how would I know if it worked? Short of refreshing the page looking for specific changes and asking Tuli to create a GitHub account, we were deploying in the dark.</p><p>I returned to my CloudFormation template and added some more functionality. When a GET request to the same URL came through, the Lambda function would respond with HTML displaying the status. This status is either that the project was currently being deployed, or how long ago the project was last deployed. For bonus points, I added a simple JavaScript setTimeout to refresh the page periodically.</p><h3>Conclusion</h3><p>Finally, the project had reached maturity and was ready for regular use, sans developer effort. Tuli had a control panel ready at a moment’s notice, including ways to edit content, upload images, deploy changes, and monitor the deployment. This could even be done from a mobile device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHf71Aua2F475XKLHPXD1g.png" /><figcaption>Notion control panel for tuli.space</figcaption></figure><p>Not too shabby for a static site on a budget.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=473a1ba25439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple LLM Tool Calling in Laravel using Prism]]></title>
            <link>https://medium.com/@brice_hartmann/simple-llm-tool-calling-in-laravel-using-prism-92cc64b0d69c?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/92cc64b0d69c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 07:57:23 GMT</pubDate>
            <atom:updated>2025-12-22T07:57:23.290Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was originally posted on </em><a href="https://brice.codes/posts/simple-llm-tool-calling-in-laravel-using-prism.html"><em>brice.codes</em></a><em>.</em></p><h3>Overview</h3><p>This article demonstrates implementing LLM tool calling in Laravel using the Prism package.</p><blockquote>Tool calling enables an LLM to invoke external functions, query databases, or call APIs to retrieve real-time information and perform actions beyond its training data. This is a foundational pattern for building agentic AI applications.</blockquote><h4>End goal</h4><p>We’ll build an <a href="https://laravel.com/docs/12.x/artisan#writing-commands">artisan command</a> that responds to natural language queries about Chicago bus stops and arrivals. The LLM will autonomously choose which tools to call based on the user’s question, be it searching for a bus stop by name, finding the nearest stop to an address, or checking arrival times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*IVVhOhlXXs4FTp5rNysLhQ.gif" /></figure><h4>Repository</h4><p>A repository for this article can be found on <a href="https://github.com/bricehartmann/laravel-llm-cta-bus-tracker">here on GitHub</a>.</p><h4>Key technologies</h4><p><strong>Services</strong></p><ul><li><a href="https://claude.com/platform/api">Claude API</a> provides the LLM that orchestrates tool calls</li><li><a href="https://opencagedata.com/">OpenCage Geocoding API</a> converts addresses to coordinates for proximity searches</li><li><a href="https://www.transitchicago.com/developers/bustracker/">Chicago Transit Authority Bus Tracker API</a> provides real-time bus arrival predictions</li></ul><p><strong>Packages</strong></p><ul><li><a href="https://prismphp.com/">Prism</a> abstracts LLM providers with a unified API for tool calling and structured output</li><li><a href="https://laravel.com/docs/12.x/scout">Laravel Scout (with Meilisearch)</a> enables fuzzy search to handle imprecise user input</li><li><a href="https://github.com/MatanYadaev/laravel-eloquent-spatial/tree/master">Laravel Eloquent Spatial</a> adds geospatial query support for finding nearest stops</li><li><a href="https://github.com/plin-code/kml-parser">Laravel KML Parser</a> parses CTA’s geographic data export</li></ul><p><strong>Prerequisites</strong></p><ul><li>A working <a href="https://laravel.com/docs/12.x/installation">Laravel</a> development environment</li><li>A <a href="https://claude.ai/login?returnTo=%2Fnew%3F">Claude API key</a> (new accounts receive free credits)</li><li>An <a href="https://opencagedata.com/users/sign_up">OpenCage Geocoding API key</a> (free tier available)</li><li>A <a href="https://www.transitchicago.com/developers/bustracker/">CTA Bus Tracker API key</a> (free, requires application)</li></ul><h3>Getting started</h3><h4>Generating a new project</h4><pre>laravel new laravel-llm-cta-bus-tracker<br>cd laravel-llm-cta-bus-tracker</pre><h4>Enums, migrations, and models</h4><p>We’ll start by creating the data layer: string-backed enums (whose values match the CTA API responses), a migration, and a model for bus stops.</p><p><strong>Enums</strong></p><p>Create the BusDirection enum:</p><p>📁 app/Enums/BusDirection.php</p><pre>&lt;?php<br> <br>namespace App\Enums;<br> <br>enum BusDirection: string <br>{<br>    case NORTH_BOUND = &#39;NB&#39;;<br>    case SOUTH_BOUND = &#39;SB&#39;;<br>    case EAST_BOUND = &#39;EB&#39;;<br>    case WEST_BOUND = &#39;WB&#39;;<br>    case NORTHEAST_BOUND = &#39;NEB&#39;;<br>    case NORTHWEST_BOUND = &#39;NWB&#39;;<br>    case SOUTHEAST_BOUND = &#39;SEB&#39;;<br>    case SOUTHWEST_BOUND = &#39;SWB&#39;;<br>}</pre><p>And the BusStopPosition enum:</p><p>📁 app/Enums/BusStopPosition.php</p><pre>&lt;?php<br> <br>namespace App\Enums;<br> <br>enum BusStopPosition: string <br>{<br>    case FAR_SIDE_OF_INTERSECTION = &#39;FS&#39;;<br>    case NEAR_SIDE_OF_INTERSECTION = &#39;NS&#39;;<br>    case NEAR_SIDE_OF_T_INTERSECTION = &#39;NT&#39;;<br>    case MIDDLE_OF_BLOCK = &#39;MB&#39;;<br>    case MIDDLE_OF_T_INTERSECTION = &#39;MT&#39;;<br>    case FAR_SIDE_OF_T_INTERSECTION = &#39;FT&#39;;<br>    case TERMINAL = &#39;TERM&#39;;<br>}</pre><p><strong>Migration</strong></p><p>Create the migration for the bus_stops table:</p><pre>php artisan make:migration CreateBusStopsTable</pre><p>📁 database/migrations/YYYY_MM_DD_HHIISS_create_bus_stops_table.php</p><pre>&lt;?php<br> <br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br> <br>return new class extends Migration<br>{<br>    public function up(): void <br>    {<br>        Schema::create(&#39;bus_stops&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;stop_identifier&#39;)-&gt;unique();<br>            $table-&gt;string(&#39;name&#39;);<br>            $table-&gt;geometry(&#39;location&#39;, subtype: &#39;point&#39;);<br>            $table-&gt;string(&#39;direction&#39;, 5);<br>            $table-&gt;string(&#39;position&#39;, 5);<br>            $table-&gt;timestamps();<br>        });<br>    }<br> <br>    public function down(): void<br>    {<br>        Schema::dropIfExists(&#39;bus_stops&#39;);<br>    }<br>};</pre><p><strong>Model</strong></p><p>Create the BusStop model with fillable attributes and enum casts:</p><pre>php artisan make:model BusStop</pre><p>📁 app/Models/BusStop.php</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use App\Enums\BusDirection;<br>use App\Enums\BusStopPosition;<br>use Illuminate\Database\Eloquent\Model;<br> <br>class BusStop extends Model <br>{<br>    protected $fillable = [<br>        &#39;stop_identifier&#39;,<br>        &#39;name&#39;,<br>        &#39;location&#39;,<br>        &#39;direction&#39;,<br>        &#39;position&#39;,<br>    ];<br> <br>    protected $casts = [<br>        &#39;direction&#39; =&gt; BusDirection::class,<br>        &#39;position&#39; =&gt; BusStopPosition::class,<br>    ];<br>}</pre><h3>Geospatial support</h3><p>To sort bus stops by distance from a location, we’ll use the matanyadaev/laravel-eloquent-spatial package:</p><pre>composer require matanyadaev/laravel-eloquent-spatial</pre><p>📁 app/Providers/AppServiceProvider.php</p><pre>&lt;?php<br> <br>namespace App\Providers;<br> <br>use Illuminate\Support\ServiceProvider;<br>use MatanYadaev\EloquentSpatial\EloquentSpatial;  // add this line<br>use MatanYadaev\EloquentSpatial\Enums\Srid; // add this line<br> <br>class AppServiceProvider extends ServiceProvider<br>{<br>    public function register(): void<br>    {<br>    }<br> <br>    public function boot(): void <br>    {<br>        // add this line<br>        EloquentSpatial::setDefaultSrid(Srid::WGS84);<br>    }<br>}</pre><p>Update the BusStop model to use the HasSpatial trait and cast location to Point:</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use App\Enums\BusDirection;<br>use App\Enums\BusStopPosition;<br>use Illuminate\Database\Eloquent\Model;<br>use MatanYadaev\EloquentSpatial\Objects\Point; // add this line<br>use MatanYadaev\EloquentSpatial\Traits\HasSpatial; // add this line<br> <br>class BusStop extends Model<br>{<br>    use HasSpatial; // add this line<br> <br>    protected $fillable = [<br>        &#39;stop_identifier&#39;,<br>        &#39;name&#39;,<br>        &#39;location&#39;,<br>        &#39;direction&#39;,<br>        &#39;position&#39;,<br>    ];<br> <br>    protected $casts = [<br>        &#39;location&#39; =&gt; Point::class, // add this line<br>        &#39;direction&#39; =&gt; BusDirection::class,<br>        &#39;position&#39; =&gt; BusStopPosition::class,<br>    ];<br>}</pre><h3>KMZ/KML file support</h3><p>Add the plin-code/kml-parser package.</p><pre>composer require plin-code/kml-parser</pre><p><strong>Bus stop data</strong></p><p>We need to populate the bus_stops table with data from CTA&#39;s public geographic dataset. For this, we&#39;ll create an artisan command.</p><pre>php artisan make:command FillBusStopsTable</pre><p>The command will:</p><ol><li>Download a <a href="https://developers.google.com/kml/documentation/kmzarchives">KMZ</a> archive from CTA’s data portal</li><li>Extract the <a href="https://developers.google.com/kml/documentation/kml_tut">KML</a> document and parse stop data (identifier, name, coordinates, direction, position)</li><li>Truncate and repopulate the bus_stops table</li></ol><p>📁 app/Console/Commands/FillBusStopsTable.php</p><pre>&lt;?php<br> <br>namespace App\Console\Commands;<br> <br>use App\Enums\BusDirection;<br>use App\Enums\BusStopPosition;<br>use App\Models\BusStop;<br>use Illuminate\Console\Command;<br>use Illuminate\Support\Facades\DB;<br>use Illuminate\Support\Facades\File;<br>use Illuminate\Support\Facades\Http;<br>use MatanYadaev\EloquentSpatial\Objects\Point;<br>use PlinCode\KmlParser\KmlParser;<br>use RuntimeException;<br> <br>class FillBusStopsTable extends Command<br>{<br>    /**<br>     * The name and signature of the console command.<br>     *<br>     * @var string<br>     */<br>    protected $signature = &#39;app:fill-bus-stops-table&#39;;<br> <br>    /**<br>     * The console command description.<br>     *<br>     * @var string<br>     */<br>    protected $description = &#39;Fill bus stops table&#39;;<br> <br>    /**<br>     * Execute the console command.<br>     */<br>    public function handle(): int<br>    {<br>        $this-&gt;line(&#39;Downloading KMZ archive...&#39;);<br>        $kmzPath = $this-&gt;downloadKmz();<br> <br>        $this-&gt;line(&#39;Loading KML document from KMZ archive...&#39;);<br>        $kml = \PlinCode\KmlParser\Facades\KmlParser::loadFromKmz($kmzPath);<br> <br>        $this-&gt;line(&#39;Deleting KMZ archive...&#39;);<br>        File::delete($kmzPath);<br> <br>        $this-&gt;line(&#39;Extracting data from KML...&#39;);<br>        $data = $this-&gt;extractData($kml);<br> <br>        $this-&gt;line(&#39;Truncating table...&#39;);<br>        DB::table(&#39;bus_stops&#39;)-&gt;truncate();<br> <br>        $this-&gt;line(&#39;Inserting data...&#39;);<br>        $this-&gt;fillTable($data);<br> <br>        $this-&gt;getOutput()-&gt;newLine();<br> <br>        $this-&gt;info(&#39;Filled bus_stops table with &#39;.count($data).&#39; records.&#39;);<br> <br>        return static::SUCCESS;<br>    }<br> <br>    protected function downloadKmz(): string<br>    {<br>        // see: https://www.transitchicago.com/data/<br>        $kmz = Http::get(&#39;https://data.cityofchicago.org/download/84eu-buny/application%2Fvnd.google-earth.kmz&#39;)<br>            -&gt;body();<br> <br>        $path = storage_path(&#39;app/private/cta-bus-stops.kmz&#39;);<br> <br>        if (! File::put($path, $kmz)) {<br>            throw new RuntimeException(&#39;Error writing KMZ file&#39;);<br>        }<br> <br>        return $path;<br>    }<br> <br>    protected function extractData(KmlParser $kml): array<br>    {<br>        $data = [];<br> <br>        foreach ($kml-&gt;getPlacemarks() as $index =&gt; $placemark) {<br>            $stopId = $this-&gt;extractFromHtml($placemark[&#39;description&#39;], &#39;SYSTEMSTOP&#39;);<br> <br>            if (! $stopId) {<br>                $this-&gt;warn(&quot;Failed to find system stop for index: $index&quot;);<br> <br>                continue;<br>            }<br> <br>            $direction = $this-&gt;extractFromHtml($placemark[&#39;description&#39;], &#39;DIR&#39;);<br> <br>            if (! $direction) {<br>                $this-&gt;warn(&quot;Failed to find direction for stop: $stopId&quot;);<br> <br>                continue;<br>            }<br> <br>            $position = $this-&gt;extractFromHtml($placemark[&#39;description&#39;], &#39;POS&#39;);<br> <br>            if (! $position) {<br>                $this-&gt;warn(&quot;Failed to find position for stop: $stopId&quot;);<br> <br>                continue;<br>            }<br> <br>            $name = $placemark[&#39;name&#39;];<br>            $latitude = $placemark[&#39;coordinates&#39;][&#39;latitude&#39;] ?? false;<br>            $longitude = $placemark[&#39;coordinates&#39;][&#39;longitude&#39;] ?? false;<br> <br>            if (! $latitude || ! $longitude) {<br>                $this-&gt;warn(&quot;Failed to find lat/lng for stop: $stopId&quot;);<br> <br>                continue;<br>            }<br> <br>            $data[] = [<br>                &#39;stop_identifier&#39; =&gt; $stopId,<br>                &#39;name&#39; =&gt; $name,<br>                &#39;latitude&#39; =&gt; $latitude,<br>                &#39;longitude&#39; =&gt; $longitude,<br>                &#39;direction&#39; =&gt; BusDirection::from($direction),<br>                &#39;position&#39; =&gt; BusStopPosition::from($position),<br>            ];<br>        }<br> <br>        return $data;<br>    }<br> <br>    protected function fillTable(array $data): void<br>    {<br>        $this-&gt;withProgressBar($data, fn ($datum) =&gt; BusStop::create([<br>            &#39;stop_identifier&#39; =&gt; $datum[&#39;stop_identifier&#39;],<br>            &#39;name&#39; =&gt; $datum[&#39;name&#39;],<br>            &#39;location&#39; =&gt; new Point($datum[&#39;latitude&#39;], $datum[&#39;longitude&#39;]),<br>            &#39;direction&#39; =&gt; $datum[&#39;direction&#39;],<br>            &#39;position&#39; =&gt; $datum[&#39;position&#39;],<br>        ]));<br>    }<br> <br>    protected function extractFromHtml(string $html, string $identifier): ?string<br>    {<br>        preg_match(&quot;/&lt;td&gt;$identifier&lt;\/td&gt;\s*&lt;td&gt;(.+)&lt;\/td&gt;/&quot;, $html, $matches);<br> <br>        return $matches[1] ?? null;<br>    }</pre><p><em>The code above uses Regular Expressions to extract data from a predictable HTML pattern. In a production application, regex should not be considered reliable for processing HTML. For this demonstration, however, it’s working just fine.</em></p><h3>Fuzzy searching</h3><p>When an LLM generates tool calls, the input may not exactly match our data. A user might ask about “Madison and State” when the database contains “Madison &amp; State St”. Fuzzy search handles these discrepancies gracefully.</p><p>We’ll use Meilisearch with Laravel Scout for <a href="https://en.wikipedia.org/wiki/Approximate_string_matching">approximate string matching</a>:</p><pre>composer require laravel/scout<br>php artisan vendor:publish --provider=&quot;Laravel\Scout\ScoutServiceProvider&quot;<br>composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle</pre><p>Add the Meilisearch configuration to .env:</p><pre>SCOUT_DRIVER=meilisearch<br>MEILISEARCH_HOST=http://127.0.0.1:7700<br>MEILISEARCH_KEY=LARAVEL-HERD</pre><p>Add the Searchable trait to BusStop and define which fields to index:</p><p>📁 app/Models/BusStop.php</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use App\Enums\BusDirection;<br>use App\Enums\BusStopPosition;<br>use Illuminate\Database\Eloquent\Model;<br>use Laravel\Scout\Searchable; // add this line<br>use MatanYadaev\EloquentSpatial\Objects\Point;<br>use MatanYadaev\EloquentSpatial\Traits\HasSpatial;<br> <br>class BusStop extends Model<br>{<br>    use HasSpatial;<br>    use Searchable; //add this line<br> <br>    protected $fillable = [<br>        &#39;stop_identifier&#39;,<br>        &#39;name&#39;,<br>        &#39;location&#39;,<br>        &#39;direction&#39;,<br>        &#39;position&#39;,<br>    ];<br> <br>    protected $casts = [<br>        &#39;location&#39; =&gt; Point::class,<br>        &#39;direction&#39; =&gt; BusDirection::class,<br>        &#39;position&#39; =&gt; BusStopPosition::class,<br>    ];<br> <br>    // add this method<br>    public function toSearchableArray(): array  <br>    {<br>        return [<br>            &#39;name&#39; =&gt; $this-&gt;name,<br>            &#39;direction&#39; =&gt; $this-&gt;direction-&gt;value,<br>        ];<br>    }<br>}</pre><p><em>We include </em><em>direction in the searchable array to enable filtering search results by travel direction.</em></p><p>Configure the direction attribute as filterable in config/scout.php:</p><pre>&lt;?php<br> <br>return [<br>    // etc...<br> <br>    &#39;meilisearch&#39; =&gt; [ <br>        &#39;host&#39; =&gt; env(&#39;MEILISEARCH_HOST&#39;, &#39;http://localhost:7700&#39;),<br>        &#39;key&#39; =&gt; env(&#39;MEILISEARCH_KEY&#39;),<br>        // add this entry<br>        &#39;index-settings&#39; =&gt; [<br>            \App\Models\BusStop::class =&gt; [<br>                &#39;filterableAttributes&#39; =&gt; [&#39;direction&#39;],<br>            ],<br>        ],<br>    ],<br>]</pre><p>Sync the index settings with Meilisearch (required for filterable attributes to work):</p><pre>php artisan scout:sync-index-settings</pre><h3>Using LLMs in Laravel with Prism</h3><p><a href="https://prismphp.com/">Prism</a> provides a unified API for working with LLM providers in Laravel. Among other things, it supports tool calling, structured output, and text output.</p><h4>Installation and configuration</h4><pre>composer require prism-php/prism<br>php artisan vendor:publish --tag=prism-config</pre><p>Add your Anthropic API key to .env:</p><pre>ANTHROPIC_API_KEY=your-api-key-here</pre><h4>Tools</h4><p>Tool calling follows a request-response cycle:</p><ol><li>You send a prompt to the LLM along with tool definitions (name, description, parameters)</li><li>The LLM decides which tool(s) to call and returns a structured request with the tool name and arguments</li><li>Your application executes the tool and sends the result back to the LLM</li><li>The LLM either calls another tool or returns a final response</li></ol><p>Prism handles this loop automatically. We just need to define our tools.</p><p><strong>Search for bus stop</strong></p><p>Our first tool searches the database using Laravel Scout. Each Prism tool defines:</p><ul><li>for() tells the LLM when to use this tool</li><li>withStringParameter() and withEnumParameter() defines the tool&#39;s inputs</li><li>__invoke() executes when the LLM calls the tool</li></ul><p>📁 app/Tools/BusStopSearchTool.php</p><pre>&lt;?php<br> <br>namespace App\Tools;<br> <br>use App\Enums\BusDirection;<br>use App\Models\BusStop;<br>use Prism\Prism\Tool;<br> <br>class BusStopSearchTool extends Tool<br>{<br>    public function __construct()<br>    {<br>        $this<br>            -&gt;as(&#39;search_bus_stops&#39;)<br>            -&gt;for(&#39;useful when you need to search for bus stops by name&#39;)<br>            -&gt;withStringParameter(<br>                name: &#39;name&#39;,<br>                description: &#39;The name of the bus stop; typically cross streets.&#39;,<br>            )<br>            -&gt;withEnumParameter(<br>                name: &#39;direction&#39;,<br>                description: &#39;The travel direction of the bus stop.&#39;,<br>                options: collect(BusDirection::cases())<br>                    -&gt;map(fn ($direction) =&gt; $direction-&gt;name)<br>                    -&gt;all(),<br>                required: false<br>            )<br>            -&gt;using($this);<br>    }<br> <br>    public function __invoke(string $name, ?string $direction = null): string<br>    {<br>        $dir = $direction &amp;&amp; defined(BusDirection::class.&#39;::&#39;.$direction)<br>            ? constant(BusDirection::class.&#39;::&#39;.$direction)<br>            : null;<br> <br>        $search = str_replace(&#39; and &#39;, &#39; &amp; &#39;, $name);<br> <br>        $busStops = BusStop::search($search)<br>            -&gt;when($dir, fn ($query) =&gt; $query-&gt;where(&#39;direction&#39;, $dir-&gt;value))<br>            -&gt;take($dir ? 3 : 6)<br>            -&gt;get();<br> <br>        return view(&#39;prompts.bus-stop-search-results&#39;, [<br>            &#39;stops&#39; =&gt; $busStops,<br>        ])-&gt;render();<br>    }<br>}</pre><p>The tool returns data via a Blade template which is a simple way to format structured responses for the LLM:</p><p>📁 resources/views/prompts/bus-stop-search-results.blade.php</p><pre>@foreach($stops as $stop)<br>bus_stop_id: {{ $stop-&gt;stop_identifier }}, bus_stop_name: {{ $stop-&gt;name }}, bus_direction: {{ $stop-&gt;direction-&gt;name }}, bus_stop_position: {{ $stop-&gt;position-&gt;name }}<br>@endforeach</pre><p><strong>Find nearest bust stop</strong></p><p>This tool geocodes an address and finds the closest bus stop using spatial queries.</p><p>Add the OpenCage API key to .env:</p><pre>OPENCAGEDATA_API_KEY=your-api-key-here</pre><p>And the service configuration:</p><p>📁 config/services.php</p><pre>&lt;?php<br> <br>return [<br>    // etc...<br> <br>    &#39;opencagedata&#39; =&gt; [ <br>        &#39;key&#39; =&gt; env(&#39;OPENCAGEDATA_API_KEY&#39;),<br>        &#39;url&#39; =&gt; &#39;https://api.opencagedata.com/geocode/v1/json&#39;,<br>    ],<br>];</pre><p>The tool geocodes the address (appending “Chicago, IL, USA” if needed) and queries for the nearest stop:</p><p>📁 app/Tools/BusStopNearestTool.php</p><pre>&lt;?php<br> <br>namespace App\Tools;<br> <br>use App\Enums\BusDirection;<br>use App\Models\BusStop;<br>use Illuminate\Support\Facades\Http;<br>use MatanYadaev\EloquentSpatial\Objects\Point;<br>use Prism\Prism\Tool;<br>use RuntimeException;<br> <br>class BusStopNearestTool extends Tool<br>{<br>    public function __construct()<br>    {<br>        $this<br>            -&gt;as(&#39;nearest_bus_stop&#39;)<br>            -&gt;for(&#39;useful when you need to search for bus stops nearest to an address&#39;)<br>            -&gt;withStringParameter(<br>                name: &#39;address&#39;,<br>                description: &#39;The address of the location to search from&#39;,<br>            )<br>            -&gt;withEnumParameter(<br>                name: &#39;direction&#39;,<br>                description: &#39;The travel direction of the bus stop.&#39;,<br>                options: collect(BusDirection::cases())<br>                    -&gt;map(fn ($direction) =&gt; $direction-&gt;name)<br>                    -&gt;all(),<br>                required: false<br>            )<br>            -&gt;using($this);<br>    }<br> <br>    public function __invoke(string $address, ?string $direction = null): string<br>    {<br>        if (! stristr($address, &#39;chicago&#39;)) {<br>            $address .= &#39;, &#39;.&#39;Chicago, IL, USA&#39;;<br>        }<br> <br>        $point = $this-&gt;geocodeAddress($address);<br> <br>        $dir = $direction &amp;&amp; defined(BusDirection::class.&#39;::&#39;.$direction)<br>            ? constant(BusDirection::class.&#39;::&#39;.$direction)<br>            : null;<br> <br>        $nearestStop = BusStop::orderByDistance(&#39;location&#39;, $point)<br>            -&gt;when($dir, fn ($query) =&gt; $query-&gt;where(&#39;direction&#39;, $dir-&gt;value))<br>            -&gt;first();<br> <br>        if (! $nearestStop) {<br>            throw new RuntimeException(&#39;Could not determine nearest bus stop&#39;);<br>        }<br> <br>        return view(&#39;prompts.bus-stop-search-results&#39;, [<br>            &#39;stops&#39; =&gt; [$nearestStop],<br>        ])-&gt;render();<br>    }<br> <br>    protected function geocodeAddress(string $address): Point<br>    {<br>        $response = Http::get(config(&#39;services.opencagedata.url&#39;), [<br>            &#39;key&#39; =&gt; config(&#39;services.opencagedata.key&#39;),<br>            &#39;q&#39; =&gt; $address,<br>            &#39;countrycode&#39; =&gt; &#39;us&#39;,<br>            &#39;proximity&#39; =&gt; &#39;41.881832,-87.623177&#39;, // center of chicago<br>        ]);<br> <br>        if (! $response-&gt;successful()) {<br>            throw new RuntimeException(&#39;Unable to geocode address&#39;);<br>        }<br> <br>        $lat = $response-&gt;json(&#39;results.0.geometry.lat&#39;);<br>        $lng = $response-&gt;json(&#39;results.0.geometry.lng&#39;);<br> <br>        if (! $lat || ! $lng) {<br>            throw new RuntimeException(&#39;Unable to find lat/lng from results&#39;);<br>        }<br> <br>        return new Point($lat, $lng);<br>    }<br>}</pre><p><strong>Next bus estimated arrival</strong></p><p>Our final tool queries the CTA Bus Tracker API for real-time arrival predictions.</p><p>Add the CTA API key to .env:</p><pre>CTABUSTRACKER_API_KEY=your-api-key-here</pre><p>Add the service configuration:</p><p>📁 config/services.php</p><pre>&lt;?php<br> <br>return [<br>    // etc...<br> <br>    &#39;ctabustracker&#39; =&gt; [  <br>        &#39;key&#39; =&gt; env(&#39;CTABUSTRACKER_API_KEY&#39;),<br>        &#39;url&#39; =&gt; &#39;https://ctabustracker.com/bustime/api/v2&#39;,<br>    ],<br>];</pre><p>The tool calls the CTA API’s /getpredictions endpoint and returns the minutes until arrival:</p><p>📁 app/Tools/BusStopNextArrivalTool.php</p><pre>&lt;?php<br> <br>namespace App\Tools;<br> <br>use Illuminate\Support\Facades\Http;<br>use Prism\Prism\Tool;<br>use RuntimeException;<br> <br>class BusStopNextArrivalTool extends Tool<br>{<br>    public function __construct()<br>    {<br>        $this<br>            -&gt;as(&#39;next_bus_arrival&#39;)<br>            -&gt;for(&#39;useful when you need to determine when the next bus will arrive at a specific stop&#39;)<br>            -&gt;withStringParameter(<br>                name: &#39;bus_stop_id&#39;,<br>                description: &#39;The ID of the bus stop&#39;,<br>            )<br>            -&gt;using($this);<br>    }<br> <br>    public function __invoke(string $bus_stop_id): string<br>    {<br>        return $this-&gt;predictNextBus($bus_stop_id).&#39; minutes&#39;;<br>    }<br> <br>    protected function predictNextBus(string $busStopId): int<br>    {<br>        $response = Http::get(config(&#39;services.ctabustracker.url&#39;) . &#39;/getpredictions&#39;, [<br>            &#39;key&#39; =&gt; config(&#39;services.ctabustracker.key&#39;),<br>            &#39;stpid&#39; =&gt; $busStopId,<br>            &#39;format&#39; =&gt; &#39;json&#39;,<br>        ]);<br> <br>        if (! $response-&gt;successful()) {<br>            throw new RuntimeException(&#39;Unable to predict next bus&#39;);<br>        }<br> <br>        $minutes = $response-&gt;json(&#39;bustime-response.prd.0.prdctdn&#39;);<br> <br>        if ($minutes === null) {<br>            throw new RuntimeException(&#39;Unable to find next bus prediction from results&#39;);<br>        }<br> <br>        return strtolower($minutes) === &#39;due&#39; ? 0 : (int) $minutes;<br>    }<br>}</pre><h4>Putting it all together</h4><p>Now we’ll create the artisan command that orchestrates everything.</p><p>Our approach uses two LLM calls:</p><ol><li>Structured output with tools: The LLM calls our tools and returns data in a defined schema. This ensures we get reliable, typed data regardless of how the LLM phrases things.</li><li>Text formatting: A second call converts the structured data into a natural language response.</li></ol><p>Create the system prompt for the structured output call:</p><p>📁 resources/views/prompts/bus-finder-structured.blade.php</p><pre>You are an assistant that determines information about the nearest bus stop and/or the next bus arrival at a stop.</pre><p>And the prompt for formatting the structured data into a sentence:</p><p>📁 resources/views/prompts/bus-finder-formatted.blade.php</p><pre>Use this information to answer the subsequent question. Ignore any `null` fields. Do not add any markdown formatting. Respond with a single sentence and nothing else.<br> <br>{{ collect($data)-&gt;map(fn ($value, $key) =&gt; &quot;$key: $value&quot;)-&gt;implode(&#39;, &#39;) }}</pre><p>Make the new command.</p><pre>php artisan make:command BusFinder</pre><p>Key aspects of the implementation:</p><ul><li>withMaxSteps(3) allows up to 3 iterations of the tool-calling loop</li><li>withSchema() defines the expected output structure using Prism&#39;s schema classes</li><li>withToolChoice(ToolChoice::Any) lets the LLM decide which tool(s) to call</li><li>PromptsForMissingInput automatically prompts for the query if not provided</li></ul><p>📁 app/Console/Commands/BusFinder.php</p><pre>&lt;?php<br> <br>namespace App\Console\Commands;<br> <br>use App\Enums\BusDirection;<br>use App\Enums\BusStopPosition;<br>use App\Tools\BusStopNearestTool;<br>use App\Tools\BusStopNextArrivalTool;<br>use App\Tools\BusStopSearchTool;<br>use Illuminate\Console\Command;<br>use Illuminate\Contracts\Console\PromptsForMissingInput;<br>use Prism\Prism\Enums\Provider;<br>use Prism\Prism\Enums\ToolChoice;<br>use Prism\Prism\Facades\Prism;<br>use Prism\Prism\Facades\Tool;<br>use Prism\Prism\Schema\EnumSchema;<br>use Prism\Prism\Schema\NumberSchema;<br>use Prism\Prism\Schema\ObjectSchema;<br>use Prism\Prism\Schema\StringSchema;<br> <br>use function Laravel\Prompts\spin;<br> <br>class BusFinder extends Command implements PromptsForMissingInput<br>{<br>    protected const string MODEL = &#39;claude-sonnet-4-5-20250929&#39;;<br> <br>    /**<br>     * The name and signature of the console command.<br>     *<br>     * @var string<br>     */<br>    protected $signature = &#39;app:bus-finder {query}&#39;;<br> <br>    /**<br>     * The console command description.<br>     *<br>     * @var string<br>     */<br>    protected $description = &#39;Find a bus stop or next bus&#39;;<br> <br>    /**<br>     * Execute the console command.<br>     */<br>    public function handle(): int<br>    {<br>        spin(<br>            callback: function () use (&amp;$formatted) {<br>                $response = Prism::structured()<br>                    -&gt;using(Provider::Anthropic, static::MODEL)<br>                    -&gt;withMaxSteps(3)<br>                    -&gt;withProviderOptions([&#39;use_tool_calling&#39; =&gt; true])<br>                    -&gt;withSchema($this-&gt;getOutputSchema())<br>                    -&gt;withSystemPrompt(view(&#39;prompts.bus-finder-structured&#39;))<br>                    -&gt;withPrompt($this-&gt;argument(&#39;query&#39;))<br>                    -&gt;withTools([<br>                        Tool::make(BusStopSearchTool::class),<br>                        Tool::make(BusStopNearestTool::class),<br>                        Tool::make(BusStopNextArrivalTool::class),<br>                    ])<br>                    -&gt;withToolChoice(ToolChoice::Any)<br>                    -&gt;asStructured();<br> <br>                $formatted = Prism::text()<br>                    -&gt;using(Provider::Anthropic, static::MODEL)<br>                    -&gt;withSystemPrompt(view(&#39;prompts.bus-finder-formatted&#39;, [&#39;data&#39; =&gt; $response-&gt;structured]))<br>                    -&gt;withPrompt($this-&gt;argument(&#39;query&#39;))<br>                    -&gt;asText();<br>            },<br>            message: &#39;thinking...&#39;,<br>        );<br> <br>        $this-&gt;info($formatted-&gt;text);<br> <br>        return static::SUCCESS;<br>    }<br> <br>    protected function getOutputSchema(): ObjectSchema<br>    {<br>        return new ObjectSchema(<br>            name: &#39;bus_finder_results&#39;,<br>            description: &#39;Results from searching for a next bus and/or bus stop.&#39;,<br>            properties: [<br>                new StringSchema(<br>                    name: &#39;bus_stop_name&#39;,<br>                    description: &#39;The name of the bus stop&#39;,<br>                    nullable: true,<br>                ),<br>                new EnumSchema(<br>                    name: &#39;bus_direction&#39;,<br>                    description: &#39;The direction of the bus&#39;,<br>                    options: collect(BusDirection::cases())<br>                        -&gt;map(fn ($direction) =&gt; $direction-&gt;name)<br>                        -&gt;all(),<br>                    nullable: true,<br>                ),<br>                new EnumSchema(<br>                    name: &#39;bus_stop_position&#39;,<br>                    description: &#39;The position of the bus stop relative to the street&#39;,<br>                    options: collect(BusStopPosition::cases())<br>                        -&gt;map(fn ($position) =&gt; $position-&gt;name)<br>                        -&gt;all(),<br>                    nullable: true,<br>                ),<br>                new NumberSchema(<br>                    name: &#39;bus_arrival_minutes&#39;,<br>                    description: &#39;When the next bus will arrive at a specific stop, in minutes&#39;,<br>                    nullable: true,<br>                    minimum: 0,<br>                ),<br>            ],<br>        );<br>    }<br>}</pre><p><strong>Running the commands</strong></p><p>Migrate the database and populate it with bus stop data:</p><pre>php artisan migrate<br>php artisan app:fill-bus-stops-table</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ytkL1NHWUWIurni_dYxmKQ.gif" /></figure><p>Try the bus finder:</p><pre>php artisan app:bus-finder</pre><h3>Conclusion</h3><p>We built an LLM-powered CLI that autonomously searches databases, geocodes addresses, and queries external APIs — all orchestrated by Claude through Prism’s tool calling interface.</p><p>The key patterns demonstrated:</p><ul><li><strong>Tool definitions as PHP classes</strong>: encapsulate logic with clear descriptions the LLM can understand</li><li><strong>Structured output</strong>: ensure reliable, typed responses from the LLM</li><li><strong>Two-step prompting</strong>: separate data gathering from natural language formatting</li></ul><p>This pattern extends naturally to more complex scenarios: multi-turn conversations, tool chains where one tool’s output feeds another, or agents that maintain state across requests. The Prism package handles the underlying complexity, letting you focus on defining what your tools do.</p><blockquote>Did you spot a mistake in this article? Have a suggestion for how something can be improved? Even if you’d just like to comment or chat about something else, I’d love to hear from you! <a href="https://brice.codes/contact.html">Contact me</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92cc64b0d69c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Laravel Password Resets]]></title>
            <link>https://medium.com/@brice_hartmann/testing-laravel-password-resets-858c58c16b79?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/858c58c16b79</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Sat, 04 Aug 2018 05:08:42 GMT</pubDate>
            <atom:updated>2018-08-04T05:08:42.557Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is an important yet often overlooked aspect of building successful Laravel applications. This article will provide an introduction to testing applications written using the <a href="https://laravel.com/">Laravel Framework</a>.</p><p>For our purposes we’ll be writing <em>feature tests </em>that make HTTP requests to our application and then make assertions about the responses and the state of the application’s database after the request is complete. We will make minimal changes to the authentication scaffolding provided by Laravel and focus on testing the <a href="https://laravel.com/docs/5.6/passwords">Password Reset</a> feature.</p><h3>Getting Started</h3><p>Assuming you are familiar with setting up a new Laravel project, use your terminal and the Laravel installer to create a new project.</p><p>If you aren’t familiar with setting up a development environment for a new Laravel application I encourage you to check out the documentation on <a href="https://laravel.com/docs/5.6/installation">installation</a> and the Vagrant box <a href="https://laravel.com/docs/5.6/homestead">Homestead</a>.</p><p>Create a new Laravel application in the directory password-reset-testing.</p><pre>$ laravel new password-reset-testing</pre><p>Once composer has finished installing everything, change your working directory to that of the new project.</p><pre>$ cd password-reset-testing/</pre><p>Next use <a href="https://laravel.com/docs/5.6/artisan">Artisan</a> to generate the <a href="https://laravel.com/docs/5.6/authentication">authentication scaffolding</a> for our application.</p><pre>$ php artisan make:auth</pre><p>Again using Artisan, run the database migrations to create the users and password_resets tables.</p><pre>$ php artisan migrate</pre><h3>Naming Each Route</h3><p>As a best practice, each of our application’s routes should have a name. By using route names and the <a href="https://laravel.com/docs/5.6/helpers#method-route">route helper function</a> instead of hard-coding routes, the URI of a route can be easily changed in the future.</p><p>Open up routes/web.php and change the contents to match below.</p><pre><strong>&lt;?php<br></strong><br>// Welcome Route<br>Route::<em>get</em>(&#39;/&#39;, <strong>function </strong>() {<br>    <strong>return </strong>view(&#39;welcome&#39;);<br>})-&gt;name(&#39;welcome&#39;);<br><br>// Authentication Routes<br>Route::<em>get</em>(&#39;login&#39;, &#39;Auth\LoginController@showLoginForm&#39;)<br>    -&gt;name(&#39;login&#39;);<br><br>Route::<em>post</em>(&#39;login&#39;, &#39;Auth\LoginController@login&#39;)<br>    -&gt;name(&#39;login.submit&#39;);<br><br>Route::<em>post</em>(&#39;logout&#39;, &#39;Auth\LoginController@logout&#39;)<br>    -&gt;name(&#39;logout&#39;);<br><br>// Registration Routes<br>Route::<em>get</em>(&#39;register&#39;,<br>    &#39;Auth\RegisterController@showRegistrationForm&#39;)<br>    -&gt;name(&#39;register&#39;);<br><br>Route::<em>post</em>(&#39;register&#39;,<br>    &#39;Auth\RegisterController@register&#39;)<br>    -&gt;name(&#39;register.submit&#39;);<br><br>// Password Reset Routes<br>Route::<em>get</em>(&#39;password/reset&#39;,<br>    &#39;Auth\ForgotPasswordController@showLinkRequestForm&#39;)<br>    -&gt;name(&#39;password.request&#39;);<br><br>Route::<em>post</em>(&#39;password/email&#39;,<br>    &#39;Auth\ForgotPasswordController@sendResetLinkEmail&#39;)<br>    -&gt;name(&#39;password.email&#39;);<br><br>Route::<em>get</em>(&#39;password/reset/{token}&#39;,<br>    &#39;Auth\ResetPasswordController@showResetForm&#39;)<br>    -&gt;name(&#39;password.reset&#39;);<br><br>Route::<em>post</em>(&#39;password/reset&#39;,<br>    &#39;Auth\ResetPasswordController@reset&#39;)<br>    -&gt;name(&#39;password.reset.submit&#39;);<br><br>// Home Route<br>Route::<em>get</em>(&#39;/home&#39;, &#39;HomeController@index&#39;)<br>    -&gt;name(&#39;home&#39;);</pre><p>Note that we didn’t change any of the routes provided by the original Auth::routes() statement, we simply rewrote them to include names for every route.</p><h3>Editing the Base Test Case</h3><p>Before we write our tests, let’s quickly edit the base test case. Open up the file at tests/TestCase.php and edit the contents to match below.</p><pre><strong>&lt;?php<br><br>namespace </strong>Tests;<br><br><strong>use </strong>Illuminate\Foundation\Testing\DatabaseTransactions;<br><strong>use </strong>Notification;<br><strong>use </strong>Illuminate\Foundation\Testing\TestCase <strong>as </strong>BaseTestCase;<br><br><strong>abstract class </strong>TestCase <strong>extends </strong>BaseTestCase<br>{<br>    <strong>use </strong>CreatesApplication;<br>    <strong>use </strong>DatabaseTransactions;<br><br>    <em>/**<br>     * Set up the test case.<br>     */<br>    </em><strong>protected function </strong>setUp()<br>    {<br>        <strong>parent</strong>::<em>setUp</em>();<br><br>        Notification::<em>fake</em>();<br>    }<br>}</pre><p>First we import the Illuminate\Foundation\Testing\DatabaseTransactions trait and the Notification facade.</p><p>The statement use DatabaseTransactions at the top of the class tells Laravel to create a database transaction before each test and roll back the transaction after each test. This will keep our tests from affecting the state of our database; the database will be in the same starting state for each test.</p><p>We override the setUp method which is called before running each test. In this method we first call the parent setUp method then call fake on the Notification <a href="https://laravel.com/docs/5.6/mocking#mocking-facades">facade</a>. This will fake all notifications sent out during any of our tests. Within each test we can then use another method on the Notification facade to assert a notification <em>would </em>have been sent to the correct destination.</p><h3>Creating the Test Class</h3><p>Use artisan to generate a new feature test called PasswordResetTest.</p><pre>$ php artisan make:test PasswordResetTest</pre><p>Open the new file at tests/Feature/PasswordResetTest.php and edit the contents to match below.</p><pre><strong>&lt;?php<br><br>namespace </strong>Tests\Feature;<br><br><strong>use </strong>App\User;<br><strong>use </strong>Hash;<br><strong>use </strong>Illuminate\Auth\Notifications\ResetPassword;<br><strong>use </strong>Illuminate\Foundation\Testing\WithFaker;<br><strong>use </strong>Notification;<br><strong>use </strong>Password;<br><strong>use </strong>Tests\TestCase;<br><br><strong>class </strong>PasswordResetTest <strong>extends </strong>TestCase<br>{<br>    <strong>use </strong>WithFaker;<br><br>    <strong>const </strong><em>ROUTE_PASSWORD_EMAIL </em>= &#39;password.email&#39;;<br>    <strong>const </strong><em>ROUTE_PASSWORD_REQUEST </em>= &#39;password.request&#39;;<br>    <strong>const </strong><em>ROUTE_PASSWORD_RESET </em>= &#39;password.reset&#39;;<br>    <strong>const </strong><em>ROUTE_PASSWORD_RESET_SUBMIT </em>= &#39;password.reset.submit&#39;;<br><br>    <strong>const </strong><em>USER_ORIGINAL_PASSWORD </em>= &#39;secret&#39;;<br>}</pre><p>Here we’ve added import statements for the model App\User, the <a href="https://laravel.com/docs/5.6/facades">facades</a> Hash, Notification, and Password, and the notification Illuminate\Auth\Notifications\ResetPassword. We’ve also added an import statement for the trait Illuminate\Foundation\Testing\WithFaker which conveniently instantiates a <a href="https://github.com/fzaninotto/Faker">Faker</a> factory for us for use within our tests. We simply specify our class is using the WithFaker trait and each test case will have an instance of a Faker factory at $this-&gt;faker.</p><p>Within our class we replaced the example test case with a statement specifying we’re using the WithFaker trait, constants for each route name we’ll be using, and a constant for the password test users will have.</p><h3>Writing Test Cases</h3><p>We will write tests for the following cases:</p><ul><li>Showing the password reset request page</li><li>Submitting the password reset request page with an invalid email address</li><li>Submitting the password reset request page with an email address not in use</li><li>Submitting the password reset request page with a valid email address in use</li><li>Showing the reset password page</li><li>Submitting the reset password page with an invalid email address</li><li>Submitting the reset password page with an email address not in use</li><li>Submitting the reset password page with a valid email address in use and a password that does not match the password confirmation</li><li>Submitting the reset password page with a valid email address in use and a password that isn’t long enough</li><li>Submitting the reset password page with a valid email address in use and a valid password matching the password confirmation</li></ul><p>After each new test, feel free to run <a href="https://phpunit.de/">PHPUnit</a> using your terminal.</p><pre>$ ./vendor/bin/phpunit</pre><h4>Testing Showing the Password Reset Request Page</h4><p>Now it’s time to write our first test! Edit the PasswordResetTest class by adding the method below. By convention each test case method starts with test which is then recognized by PHPUnit.</p><pre><em>/**<br> * Testing showing the password reset request page.<br> */<br></em><strong>public function </strong>testShowPasswordResetRequestPage()<br>{<br>    $this<br>        -&gt;get(route(<strong>self</strong>::<em>ROUTE_PASSWORD_REQUEST</em>))<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(&#39;Reset Password&#39;)<br>        -&gt;assertSee(&#39;E-Mail Address&#39;)<br>        -&gt;assertSee(&#39;Send Password Reset Link&#39;);<br>}</pre><p>In this test case we use the method get to make a GET request to the specified URI. We generate the URI using the route helper method and the name of our route, which is stored in a constant. The assertSuccessful method asserts the response has a 200 level status code. Next we use the assertSee method to check for the presence of the text Reset Password, E-Mail Address, and Send Password Reset Link.</p><h4>Testing Submitting the Password Reset Request Page</h4><p>Our next few tests will be testing submitting the password reset request page with various inputs.</p><p>Add the next test shown below which tests submitting a password reset request with an invalid email address.</p><pre><em>/**<br> * Testing submitting the password reset request with an invalid<br> * email address.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetRequestInvalidEmail()<br>{<br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_REQUEST</em>))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_EMAIL</em>), [<br>            &#39;email&#39; =&gt; str_random(),<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;validation.email&#39;, [<br>            &#39;attribute&#39; =&gt; &#39;email&#39;,<br>        ]));<br>}</pre><p>When a request fails validation, Laravel will return a redirect to the location the request came from with validation error messages flashed to the session. To make assertions on the response the user will see, therefore, we need to follow redirects with the followingRedirects method. We also specify a location we’re making the request <em>from</em> using the from method.</p><p>Next we use the post method to issue a POST request to the password.email route (again using the route helper and a previously defined constant) with data specifying the email key as a random string (using the str_random <a href="https://laravel.com/docs/5.6/helpers#method-str-random">helper method</a>).</p><p>We assert the response is successful and check for the presence of a validation message. The __ <a href="https://laravel.com/docs/5.6/helpers#method-__">helper method</a> is used to format the validation message using <a href="https://laravel.com/docs/5.6/localization">localization files</a>. validation.email specifies the file resources/lang/{locale}/validation.php and the email array key, where {locale} is the application’s configured locale. The :attribute parameter in the string The :attribute must be a valid email address. will be replaced by the string email as specified by the associative array passed as the second argument to the __ method.</p><p>Next we’ll be testing submitting the password reset request page with a valid email address that is not in use by any user of the application.</p><p>Add the test shown below.</p><pre><em>/**<br> * Testing submitting the password reset request with an email<br> * address not in the database.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetRequestEmailNotFound()<br>{<br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_REQUEST</em>))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_EMAIL</em>), [<br>            &#39;email&#39; =&gt; $this-&gt;faker-&gt;unique()-&gt;safeEmail,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(e(__(&#39;passwords.user&#39;)));<br>}</pre><p>Again we follow redirects and set the location where our request should originate from, but this time we use Faker to generate an email address that is not in use by anyone in the world (as the domains are example.com, example.net, and example.org). We use the unique method to ensure the email address returned has not been previously returned by Faker.</p><p>We assert the response is successful and check for the presence of the validation error message specified by the user key in the associative array in the file resources/lang/{locale}/passwords.php. This time the validation message contains a reserved HTML character, &#39;, so we must use the e <a href="https://laravel.com/docs/5.6/helpers#method-e">helper method</a> to replace the character with it’s corresponding <a href="https://www.w3schools.com/html/html_entities.asp">character entity</a>.</p><p>Finally it’s time to test successfully submitting the password reset request page with a valid email address present in our application’s database.</p><p>Add the test shown below.</p><pre><em>/**<br> * Testing submitting a password reset request.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetRequest()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create();<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_REQUEST</em>))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_EMAIL</em>), [<br>            &#39;email&#39; =&gt; $user-&gt;email,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;passwords.sent&#39;));<br><br>    Notification::<em>assertSentTo</em>($user, ResetPassword::<strong>class</strong>);<br>}</pre><p>In this test we use the factory <a href="https://laravel.com/docs/5.6/helpers#method-factory">helper method</a> to create a new user in our database. Then we follow redirects for the response to our POST request to the password.email route. Our request specifies the created user’s email address in the email key of the payload. We assert the response is successful and check for the presence of the string We have e-mailed your password reset link!, specified with the argument passwords.sent passed to the __ helper method.</p><p>Using the Notification facade’s method assertSentTo we assert the ResetPassword notification was sent to the $user. We can pass the model stored in the variable $user directly into the assertSentTo method because our User model, by default, uses the Illuminate\Notifications\Notifiable <a href="https://laravel.com/docs/5.6/notifications#using-the-notifiable-trait">trait</a>. When routing emails for any model using the Notifiable trait, the email property on the model will be used by default.</p><h4>Testing Showing the Password Reset Page</h4><p>Next, to test showing the password reset page, add the test shown below.</p><pre><em>/**<br> * Testing showing the reset password page.<br> */<br></em><strong>public function </strong>testShowPasswordResetPage()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create();<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $this<br>        -&gt;get(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(&#39;Reset Password&#39;)<br>        -&gt;assertSee(&#39;E-Mail Address&#39;)<br>        -&gt;assertSee(&#39;Password&#39;)<br>        -&gt;assertSee(&#39;Confirm Password&#39;);<br>}</pre><p>We again create a user using the factory helper method. Next we create a valid password reset token using the Password facade.</p><p>The value of $token is used to replace the token parameter in the password.reset route. We send a GET request to this route, assert the response is successful, and check for the presence of the text for page elements.</p><h4>Testing Submitting the Password Rest Page</h4><p>Next we’ll test submitting the password reset page, starting with using an invalid email address.</p><p>Continue our testing by adding the test shown below.</p><pre><em>/**<br> * Testing submitting the password reset page with an invalid<br> * email address.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetInvalidEmail()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create([<br>        &#39;password&#39; =&gt; bcrypt(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>),<br>    ]);<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $password = str_random();<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET_SUBMIT</em>), [<br>            &#39;token&#39; =&gt; $token,<br>            &#39;email&#39; =&gt; str_random(),<br>            &#39;password&#39; =&gt; $password,<br>            &#39;password_confirmation&#39; =&gt; $password,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;validation.email&#39;, [<br>            &#39;attribute&#39; =&gt; &#39;email&#39;,<br>        ]));<br><br>    $user-&gt;refresh();<br><br>    $this-&gt;assertFalse(Hash::<em>check</em>($password, $user-&gt;password));<br><br>    $this-&gt;assertTrue(Hash::<em>check</em>(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>,<br>        $user-&gt;password));<br>}</pre><p>In this test we’re again using the factory helper method to create at test user but this time we explicitly set the user’s password. To do this we use the bcrypt <a href="https://laravel.com/docs/5.6/helpers#method-bcrypt">helper method</a> to hash the value of our constant.</p><p>We create another password reset token and generate a random string to use as the new password for our request’s payload. Again following redirects we POST to the password.reset.submit route with a request originating from the password.reset route. A random string is used for the email address in the request payload.</p><p>After asserting the response was successful and checking for the validation.email validation message we refresh the user model and use the check method on the Hash facade to assert the user’s password has not changed.</p><p>Next we’ll test submitting the password reset page with an email address not in use by our application’s database.</p><p>Add the test shown below.</p><pre><em>/**<br> * Testing submitting the password reset page with an email<br> * address not in the database.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetEmailNotFound()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create([<br>        &#39;password&#39; =&gt; bcrypt(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>),<br>    ]);<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $password = str_random();<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET_SUBMIT</em>), [<br>            &#39;token&#39; =&gt; $token,<br>            &#39;email&#39; =&gt; $this-&gt;faker-&gt;unique()-&gt;safeEmail,<br>            &#39;password&#39; =&gt; $password,<br>            &#39;password_confirmation&#39; =&gt; $password,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(e(__(&#39;passwords.user&#39;)));<br><br>    $user-&gt;refresh();<br><br>    $this-&gt;assertFalse(Hash::<em>check</em>($password, $user-&gt;password));<br><br>    $this-&gt;assertTrue(Hash::<em>check</em>(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>,<br>        $user-&gt;password));<br>}</pre><p>Nothing new on this test. We create a user, password reset token, and new password. Then the follow redirects, POST to the password.reset.submit route from the password.reset route using the token, a random and unique safe email, and the new password. We assert the response is successful, check for the presence of the passwords.user translated string (after swapping any html character entities in the string), refresh the user, and assert the user’s password hasn’t changed.</p><p>The next test will be testing submitting the password reset page with a password that doesn’t match the password confirmation.</p><p>Add the test shown below.</p><pre><em>/**<br> * Testing submitting the password reset page with a password<br> * that doesn&#39;t match the password confirmation.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetPasswordMismatch()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create([<br>        &#39;password&#39; =&gt; bcrypt(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>),<br>    ]);<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $password = str_random();<br>    $password_confirmation = str_random();<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET_SUBMIT</em>), [<br>            &#39;token&#39; =&gt; $token,<br>            &#39;email&#39; =&gt; $user-&gt;email,<br>            &#39;password&#39; =&gt; $password,<br>            &#39;password_confirmation&#39; =&gt; $password_confirmation,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;validation.confirmed&#39;, [<br>            &#39;attribute&#39; =&gt; &#39;password&#39;,<br>        ]));<br><br>    $user-&gt;refresh();<br><br>    $this-&gt;assertFalse(Hash::<em>check</em>($password, $user-&gt;password));<br><br>    $this-&gt;assertTrue(Hash::<em>check</em>(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>,<br>        $user-&gt;password));<br>}</pre><p>Again nothing new on this test except we’re checking for a different validation message.</p><p>Our last invalid submission case to test for submitting the password reset page is using a new password that’s too short.</p><p>Add the test shown below.</p><pre><em>/**<br> * Testing submitting the password reset page with a password<br> * that is not long enough.<br> */<br></em><strong>public function </strong>testSubmitPasswordResetPasswordTooShort()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create([<br>        &#39;password&#39; =&gt; bcrypt(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>),<br>    ]);<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $password = str_random(5);<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET_SUBMIT</em>), [<br>            &#39;token&#39; =&gt; $token,<br>            &#39;email&#39; =&gt; $user-&gt;email,<br>            &#39;password&#39; =&gt; $password,<br>            &#39;password_confirmation&#39; =&gt; $password,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;validation.min.string&#39;, [<br>            &#39;attribute&#39; =&gt; &#39;password&#39;,<br>            &#39;min&#39; =&gt; 6,<br>        ]));<br><br>    $user-&gt;refresh();<br><br>    $this-&gt;assertFalse(Hash::<em>check</em>($password, $user-&gt;password));<br><br>    $this-&gt;assertTrue(Hash::<em>check</em>(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>,<br>        $user-&gt;password));<br>}</pre><p>This time we pass an argument 5 to the str_random helper function to specify the length of the random returned string (as opposed to the default length of 16). Another difference in this test is we’re checking for the presence of a validation message, validation.min.string, with two parameters, attribute and min.</p><p>Notice how we can use dot notation to specify a translation string in a nested array. To learn more about these validation messages and translation strings, check out the file at resources/lang/{locale}/validation.php.</p><p>Finally, it’s time to test the happy path: submitting the password reset page with a valid email address belonging to a user with a valid password reset token and a password matching the confirmation password (that isn’t too short).</p><p>Add the final test shown below.</p><pre><em>/**<br> * Testing submitting the password reset page.<br> */<br></em><strong>public function </strong>testSubmitPasswordReset()<br>{<br>    $user = factory(User::<strong>class</strong>)-&gt;create([<br>        &#39;password&#39; =&gt; bcrypt(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>),<br>    ]);<br><br>    $token = Password::<em>broker</em>()-&gt;createToken($user);<br><br>    $password = str_random();<br><br>    $this<br>        -&gt;followingRedirects()<br>        -&gt;from(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET</em>, [<br>            &#39;token&#39; =&gt; $token,<br>        ]))<br>        -&gt;post(route(<strong>self</strong>::<em>ROUTE_PASSWORD_RESET_SUBMIT</em>), [<br>            &#39;token&#39; =&gt; $token,<br>            &#39;email&#39; =&gt; $user-&gt;email,<br>            &#39;password&#39; =&gt; $password,<br>            &#39;password_confirmation&#39; =&gt; $password,<br>        ])<br>        -&gt;assertSuccessful()<br>        -&gt;assertSee(__(&#39;passwords.reset&#39;));<br><br>    $user-&gt;refresh();<br><br>    $this-&gt;assertFalse(Hash::<em>check</em>(<strong>self</strong>::<em>USER_ORIGINAL_PASSWORD</em>,<br>        $user-&gt;password));<br><br>    $this-&gt;assertTrue(Hash::<em>check</em>($password, $user-&gt;password));<br>}</pre><p>In this test we use the Hash facade to assert the user’s password <em>has</em> changed to the given password, thus successfully completing the password reset.</p><h3>Conclusion</h3><p>This concludes our testing for Laravel’s password resets. In ten short tests we were able to do things like create test users and valid password reset tokens, make HTTP requests to our application, assert the response contains desired content, and check if the user’s password has changed as a result of the request.</p><p>Laravel has provided ample <a href="https://laravel.com/docs/5.6/testing">testing capabilities</a> and I strongly recommend reading the documentation for a deeper look at the possibilities.</p><p>You can view the source code for this project on <a href="https://github.com/bricehartmann/laravel-password-reset-testing">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=858c58c16b79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Geospatial Data in Laravel]]></title>
            <link>https://medium.com/@brice_hartmann/getting-started-with-geospatial-data-in-laravel-94502dc74d55?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/94502dc74d55</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 03:26:53 GMT</pubDate>
            <atom:updated>2018-08-03T20:07:46.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we’ll be learning about working with geospatial data, or data relating to geographical locations, in <a href="https://laravel.com/docs/5.6">Laravel 5.6</a>. As an exercise for working with this kind of data we’ll be building a simple USA Neighborhood Finder application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*xhis7Dk9d4i6bUKp0VdjQw.png" /><figcaption>screenshot of a successful result in our application</figcaption></figure><p>There are three main learning objectives for this article:</p><ol><li>How to use Google’s <a href="https://developers.google.com/maps/documentation/geocoding/start">Geocoding API</a> to geocode an address into corresponding coordinates consisting of a longitude and latitude.</li><li>How to import geospatial data in <a href="https://en.wikipedia.org/wiki/Well-known_text">Well-Known Text</a> (WKT) format into a <a href="https://dev.mysql.com/doc/refman/5.7/en/spatial-type-overview.html">spatial column</a> in MySQL.</li><li>How to determine if a point (in this case a longitude and latitude) is contained by a geometry (in this case a neighborhood boundary).</li></ol><h3>Overview</h3><p>The flow of our application is as follows:</p><ol><li>A user enters an address and clicks “Submit”.</li><li>The name of the neighborhood which contains the address is displayed to the user (or an error message stating no location or neighborhood could be found).</li></ol><p>For the purposes of this article we won’t be tracking down the neighborhood boundaries of every neighborhood in the USA; instead we’ll be using three example data sets but set things up so more data sources can easily be added in the future.</p><p>You can take a look at the data sources using these links:</p><ul><li><a href="https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Neighborhoods/bbvz-uum9">Chicago, IL neighborhood boundaries</a></li><li><a href="https://data.baltimorecity.gov/Neighborhoods/Neighborhoods/5cni-ybar">Baltimore, MD neighborhood boundaries</a></li><li><a href="https://data.brla.gov/dataset/Neighborhood/65ut-h6hw">East Baton Rouge Parish, Baton Rouge, LA neighborhood boundaries</a></li></ul><p>A basic schema of our application’s database is shown below. We only need two tables: Laravel’s table for <a href="https://laravel.com/docs/5.6/migrations">migrations</a> and a table for storing neighborhoods. Our spatial column will be named geometry and be of the multipolygon type. Think of a multipolygon as a collection of polygons. We’re using a multipolygon because a neighborhood may have more than one polygon to define its boundary. If a neighborhood uses a polygon to define its boundary we can always create multipolygon containing a single polygon (which we’ll be doing later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*9xMPEnuq2y5NNJZZhJq-tw.png" /><figcaption>schema of our application’s database</figcaption></figure><p>In addition to the <a href="https://laravel.com/">Laravel Framework,</a> we’ll be using two more packages to build our application:</p><ul><li><a href="https://github.com/geocoder-php/GeocoderLaravel">toin0u/geocoder-laravel</a> for using Google’s Geocoding API</li><li><a href="https://github.com/grimzy/laravel-mysql-spatial">grimzy/laravel-mysql-spatial</a> for parsing WKT geometries and determining if a multipolygon contains a point.</li></ul><p>We will also be using <a href="https://getbootstrap.com/docs/4.0/getting-started/introduction/">Bootstrap 4</a> for basic styling.</p><h3>Creating Our Application</h3><p>For this article it’s assumed you’re comfortable using a development environment for Laravel (such as <a href="https://laravel.com/docs/5.6/homestead">Homestead</a>).</p><h4>Generating the Project</h4><p>First, let’s create a new Laravel project using the terminal.</p><pre>$ laravel new neighborhood-finder</pre><p>Wait for the installation to finish and change directories to the root of the project.</p><pre>$ cd neighborhood-finder/</pre><p>Next let’s clean up some of the things Laravel comes with that we won’t be using for our application. This includes authentication controllers, the User model/migration/factory, and the password_resets table.</p><ul><li>delete the app/Http/Controllers/Auth directory</li><li>delete app/User.php</li><li>delete database/factories/UserFactory.php</li><li>delete database/migrations/*_create_users_table.php</li><li>delete database/migrations/*_create_password_resets_table.php</li></ul><p>Now we’re ready to create the model and migration for a Neighborhood. Note how we’re creating the model in the App\Models namespace.</p><pre>$ php artisan make:model Models\\Neighborhood --migration</pre><p>For our application each Neighborhood will have an (auto-incrementing) id, a name, a city, a state(abbreviation), and a geometry representing the neighborhood’s boundary as a multipolygon.</p><p>Open up the generated database/migrations/*_create_neighborhoods_table.php migration and edit the up method as shown below.</p><pre><em>/**<br> * Run the migrations.<br> *<br> * </em><strong><em>@return </em></strong><em>void<br> */<br></em><strong>public function </strong>up()<br>{<br>    Schema::<em>create</em>(&#39;neighborhoods&#39;, <strong>function </strong>(Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;string(&#39;name&#39;);<br>        $table-&gt;string(&#39;city&#39;);<br>        $table-&gt;string(&#39;state&#39;, 2);<br>        $table-&gt;multiPolygon(&#39;geometry&#39;);<br>        $table-&gt;timestamps();<br>    });<br>}</pre><h4>Installing the First Package</h4><p>Now let’s install our first package using composer: grimzy/laravel-mysql-spatial. This package will allow us to easily work with spatial data types.</p><pre>$ composer require &quot;grimzy/laravel-mysql-spatial&quot;</pre><p>Let composer install the package dependencies and regenerate autoload files.</p><h4>The Neighborhood Model</h4><p>Our Neighborhood model will be using the SpatialTrait found in the grimzy/laravel-mysql-spatial package. The package looks for any attributes defined in the $spatialFields array on a model using this trait.</p><p>Edit app/Models/Neighborhood.php to match below. Notice how a spatial field is still eligible to be fillable through mass assignment.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Models;<br><br><strong>use </strong>Grimzy\LaravelMysqlSpatial\Eloquent\SpatialTrait;<br><strong>use </strong>Illuminate\Database\Eloquent\Model;<br><br><strong>class </strong>Neighborhood <strong>extends </strong>Model<br>{<br>    <strong>use </strong>SpatialTrait;<br><br>    <em>/**<br>     * The attributes that are mass-assignable.<br>     *<br>     * </em><strong><em>@var </em></strong><em>array<br>     */<br>    </em><strong>protected </strong>$fillable = [<br>        &#39;name&#39;,<br>        &#39;geometry&#39;,<br>    ];<br><br>    <em>/**<br>     * The attributes that are spatial fields.<br>     *<br>     * </em><strong><em>@var </em></strong><em>array<br>     */<br>    </em><strong>protected </strong>$spatialFields = [<br>        &#39;geometry&#39;<br>    ];<br>}</pre><h4>Gathering Test Data</h4><p>Many cities have data portals open to the public. To seed our database with neighborhoods including geospatial data for boundaries, our application will use Comma-separated values (CSV) files exported from three of these data portals.</p><p>Create a directory at database/seeds/flat-files for a place to store the flat files.</p><p>We want to ensure none of these flat files are checked into source control, so create a <a href="https://git-scm.com/docs/gitignore">.gitignore</a> file at database/seeds/flat-files/.gitignore containing the following:</p><pre>*<br>!.gitignore</pre><p>The * entry is a wildcard telling git to ignore all files in the directory. The !.gitignore entry excludes the .gitignore file from the wildcard so it is still checked into source control.</p><p>Download the following CSV files to each location specified below.</p><ul><li><a href="https://data.cityofchicago.org/api/views/y6yq-dbs2/rows.csv?accessType=DOWNLOAD">this CSV</a> to database/seeds/flat-files/chicago-illinois.csv</li><li><a href="https://data.baltimorecity.gov/api/views/h3fx-54q3/rows.csv?accessType=DOWNLOAD">this CSV</a> to database/seeds/flat-files/baltimore-maryland.csv</li><li><a href="https://data.brla.gov/api/views/b389-9iq7/rows.csv?accessType=DOWNLOAD">this CSV</a> to database/seeds/flat-files/east-baton-rouge-parish-louisiana.csv</li></ul><p>Let’s take a quick peek at what this data looks like. Open up database/seeds/flat-files/chicago-illinois.csv and notice the file contains a header row specifying the columns. The two columns we want are PRI_NEIGH (primary neighborhood) and the_geom (the geometry data).</p><p>From the first row of data in the file, copy the MULTIPOLYGON(((...))) part. This is the WKT representation of the neighborhood’s boundary.</p><p>To visualize WKT data one of my favorite tools is Wicket by Arthur Endsley. Open up <a href="https://arthur-e.github.io/Wicket/sandbox-gmaps3.html">Wicket</a>, paste the WKT data from your clipboard into the text box, and click “Map It!”. You’ll see the mapped multipolygon for Chicago’s neighborhood Grand Boulevard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*KVKQq9sT66wLyoPYsDSt5w.png" /></figure><h4>Creating Seeders</h4><p>Now that we have our flat files and an understanding of what the data looks like let’s create some seeders.</p><p>For this exercise we’ll keep things simple with one seeder per file, each of which will extend a base class. The base class will hold logic for reading a CSV and creating a Neighborhood record. It will also contain an abstract method for transforming a geometry record into a Multipolygon. Each seeder extending the base class will implement this abstract method with logic specific to the file being processed. These seeders will also contain the run() method to be called by Laravel.</p><p>While this pattern works well for our purposes as we only have a few flat files to process, for a larger application with possibly hundreds of files I’d suggest a variation of this pattern and not defining one seeder per file.</p><p>First, let’s create our BaseNeighborhoodSeeder using artisan.</p><pre>$ php artisan make:seeder BaseNeighborhoodSeeder</pre><p>Update the created file at database/seeds/BaseNeighborhoodSeeder.php to match below.</p><pre><strong>&lt;?php<br><br>use </strong>App\Models\Neighborhood;<br><strong>use </strong>Grimzy\LaravelMysqlSpatial\Types\MultiPolygon;<br><strong>use </strong>Illuminate\Database\Seeder;<br><br><strong>abstract class </strong>BaseNeighborhoodSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Mode for opening a file as read-only.<br>     */<br>    </em><strong>const </strong><em>FILE_MODE_READ </em>= &#39;r&#39;;<br><br>    <em>/**<br>     * Parses the given geometry value into a Multipolygon.<br>     *<br>     * </em><strong><em>@param </em></strong><em>mixed $geometry the geometry to parse<br>     * </em><strong><em>@return </em></strong><em>\Grimzy\LaravelMysqlSpatial\Types\MultiPolygon<br>     */<br>    </em><strong>protected abstract function </strong>parseGeometryToMultiPolygon($geometry): MultiPolygon;<br><br>    <em>/**<br>     * Reads all records in a flat file, parses the geometry into a multipolygon,<br>     * and saves a Neighborhood in the database for each record.<br>     *<br>     * </em><strong><em>@param </em></strong><em>string $file_path path to the file to read data from<br>     * </em><strong><em>@param </em></strong><em>int $name_index the index of the column containing the neighborhood name<br>     * </em><strong><em>@param </em></strong><em>int $geometry_index the index of the column containing the neighborhood geometry<br>     * </em><strong><em>@param </em></strong><em>string $city the name of the neighborhoods&#39; city<br>     * </em><strong><em>@param </em></strong><em>string $state the name of the neighborhoods&#39; state<br>     * </em><strong><em>@param </em></strong><em>bool $skip_first_row if the first row of the file should be skipped (if there&#39;s a header row)<br>     * </em><strong><em>@param </em></strong><em>bool $use_title_case if the neighborhood names should be converted to Title Case<br>     * </em><strong><em>@throws </em></strong><em>\Throwable<br>     */<br>    </em><strong>protected function </strong>seedFromFlatFile(string $file_path,<br>                                        int $name_index,<br>                                        int $geometry_index,<br>                                        string $city,<br>                                        string $state,<br>                                        bool $skip_first_row,<br>                                        bool $use_title_case) {<br><br>        // throw an exception unless a file exists at the given location<br>        throw_unless(file_exists($file_path), <strong>new </strong>Exception(&quot;No file found at path &#39;$file_path&#39;&quot;));<br><br>        <strong>try </strong>{<br>            // open the specified file at the given location<br>            $file = fopen($file_path, <strong>self</strong>::<em>FILE_MODE_READ</em>);<br><br>            // if the first row should be skipped, read the first row of the file<br>            <strong>if </strong>($skip_first_row) {<br>                fgetcsv($file);<br>            }<br><br>            // while there&#39;s a row to be read in the file, read the next row<br>            <strong>while </strong>($row = fgetcsv($file)) {<br>                // get the neighborhood name from the specified index<br>                $name = $row[$name_index];<br><br>                // if the name should be converted to Title Case, convert it<br>                <strong>if </strong>($use_title_case) {<br>                    $name = title_case($name);<br>                }<br><br>                // parse the geometry at the specified index into a multipolygon<br>                $multipolygon = $this-&gt;parseGeometryToMultiPolygon($row[$geometry_index]);<br><br>                // make the new neighborhood model by filling the name, city, state, and geometry<br>                $neighborhood = <strong>new </strong>Neighborhood([<br>                    &#39;name&#39; =&gt; $name,<br>                    &#39;city&#39; =&gt; $city,<br>                    &#39;state&#39; =&gt; $state,<br>                    &#39;geometry&#39; =&gt; $multipolygon,<br>                ]);<br><br>                // throw an exception unless the neighborhood could be saved<br>                throw_unless($neighborhood-&gt;save(), <strong>new </strong>Exception(&quot;Failed to save neighborhood &#39;$name&#39;&quot;));<br>            }<br>        } <strong>finally </strong>{<br>            // if the file has been opened, close it<br>            <strong>if </strong>(! <strong>empty</strong>($file)) {<br>                fclose($file);<br>            }<br>        }<br>    }<br>}</pre><p>Here we’re defining an <a href="http://php.net/manual/en/language.oop5.abstract.php">abstract class</a> which cannot be instantiated; this class must be extended to be used. At the top of the class we have a constant for the file mode we’ll be using to open CSV files.</p><p>We define the abstract method parseGeometryToMulipolygon($geometry) and declare it returns a Multipolygon. This method must be implemented by any class extending BaseNeighborhoodSeeder and will contain the logic necessary for converting the geometry data in each CSV record to a Multipolygon. For our purposes this will always be parsing WKT but it could easily be parsing another format such as <a href="http://geojson.org/">GeoJSON</a>.</p><p>The seedFromFlatFile method contains parameters for the path to the file to read data from, the index of the neighborhood name column, the index of the neighborhood boundary geometry column, the name of the city for the neighborhoods, the name of the state for the neighborhoods, whether or not to skip the first row of the file (in case there is a header row), and whether or not the neighborhood name should be converted to Title Case before being saved.</p><p>In this method we first check if a file exists at $file_path using PHP’s <a href="http://php.net/manual/en/function.file-exists.php">file_exists</a> function. If a file does not exist at the specified path we throw an exception.</p><p>Next, inside a try block, we open the file for reading using <a href="http://php.net/manual/en/function.fopen.php">fopen</a> with the file mode &#39;r&#39;. If the $skip_first_row flag is true, we read the first row of the file using PHP’s function <a href="http://php.net/manual/en/function.fgetcsv.php">fgetcsv</a>. Looping through each row, while there’s still a row left to read in the file, we use fgetcsv to parse the CSV row into an array of data.</p><p>Using the given $name_index we get the neighborhood name from the array and if $use_title_case is true we use Laravel’s helper method <a href="https://laravel.com/docs/5.6/helpers#method-title-case">title_case</a> to convert the string to Title Case. The neighborhood’s geometry is parsed into a MultiPolygon by passing the data of the geometry column into the parseGeometryToMultiPolygon method, which will be implemented by child classes.</p><p>Finally we create the new neighborhood record by passing an array of attributes to the Neighborhood model’s constructor. If the model could not be saved, an exception is thrown.</p><p>In the finally block we check if the $file variable has a value and if it does, we use <a href="http://php.net/manual/en/function.fclose.php">fclose</a> to close the file. Putting this logic inside the finally block ensures we close the file even if an exception is thrown.</p><p>With our base seeder class in place, we’re ready to create a seeder for each flat file. Start by creating ChicagoIllinoisNeighborhoodSeeder using artisan.</p><pre>$ php artisan make:seeder ChicagoIllinoisNeighborhoodSeeder</pre><p>Update the file database/seeds/ChicagoIllinoisDatabaseSeeder.php with the content below.</p><pre><strong>&lt;?php<br><br>use </strong>Grimzy\LaravelMysqlSpatial\Types\MultiPolygon;<br><br><strong>class </strong>ChicagoIllinoisNeighborhoodSeeder <strong>extends </strong>BaseNeighborhoodSeeder<br>{<br>    <em>/**<br>     * Index of the name column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_NAME </em>= 0;<br><br>    <em>/**<br>     * Index of the geometry column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_GEOMETRY </em>= 1;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; city.<br>     */<br>    </em><strong>const </strong><em>CITY </em>= &#39;Chicago&#39;;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; state.<br>     */<br>    </em><strong>const </strong><em>STATE </em>= &#39;IL&#39;;<br><br>    <em>/**<br>     * Path of the seed file relative to the `database` directory.<br>     */<br>    </em><strong>const </strong><em>DATABASE_FILE_PATH </em>= &#39;seeds/flat-files/chicago-illinois.csv&#39;;<br><br>    <em>/**<br>     * If the file has a header row.<br>     */<br>    </em><strong>const </strong><em>HAS_HEADER_ROW </em>= <strong>true</strong>;<br><br>    <em>/**<br>     * If the neighborhood names should be converted to Title Case.<br>     */<br>    </em><strong>const </strong><em>USE_TITLE_CASE </em>= <strong>false</strong>;<br><br>    <em>/**<br>     * Run the database seeds.<br>     *<br>     * </em><strong><em>@throws </em></strong><em>\Throwable<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        // resolve the path of the seed file<br>        $file_path = database_path(<strong>self</strong>::<em>DATABASE_FILE_PATH</em>);<br><br>        // seed the neighborhoods from the flat file<br>        $this-&gt;seedFromFlatFile($file_path,<br>            <strong>self</strong>::<em>COLUMN_INDEX_NAME</em>,<br>            <strong>self</strong>::<em>COLUMN_INDEX_GEOMETRY</em>,<br>            <strong>self</strong>::<em>CITY</em>,<br>            <strong>self</strong>::<em>STATE</em>,<br>            <strong>self</strong>::<em>HAS_HEADER_ROW</em>,<br>            <strong>self</strong>::<em>USE_TITLE_CASE</em>);<br>    }<br><br>    <em>/**<br>     * Parses the geometry to a multipolygon from well-known text.<br>     *<br>     * </em><strong><em>@param </em></strong><em>mixed $geometry<br>     * </em><strong><em>@return </em></strong><em>\Grimzy\LaravelMysqlSpatial\Types\MultiPolygon<br>     */<br>    </em><strong>protected function </strong>parseGeometryToMultiPolygon($geometry): MultiPolygon<br>    {<br>        <strong>return </strong>MultiPolygon::<em>fromWKT</em>($geometry);<br>    }<br>}</pre><p>At the top of the file we have constants for the column indexes of the name and geometry data as well as constants for the neighborhood city, the neighborhood state, the file path relative to the database directory, whether or not the file has a header row, and whether or not the neighborhood names should be converted to Title Case.</p><p>Next we have the run method which is called by Laravel when executing the seeder. In this method we first resolve the path of the flat file using Laravel’s helper method <a href="https://laravel.com/docs/5.6/helpers#method-database-path">database_path</a>. Then we call the parent class’s method seedFromFlatFile using the file path and our constants as arguments.</p><p>Finally, we implement the parseGeometryToMultiPolygon method by using the fromWKT static method of Grimzy\LaravelMysqlSpatial\Types\Multipolygon to instantiate a new MultiPolygon and return it. Remember this method will be called by the base class during the execution of the seedFromFlatFile method.</p><p>Continuing with our seeders, use artisan to create BaltimoreMarylandSeeder.</p><pre>$ php artisan make:seeder BaltimoreMarylandSeeder</pre><p>Edit the file database/seeds/BaltimoreMarylandSeeder.php to match the contents below.</p><pre><strong>&lt;?php<br><br>use </strong>Grimzy\LaravelMysqlSpatial\Types\MultiPolygon;<br><br><strong>class </strong>BaltimoreMarylandSeeder <strong>extends </strong>BaseNeighborhoodSeeder<br>{<br>    <em>/**<br>     * Index of the name column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_NAME </em>= 3;<br><br>    <em>/**<br>     * Index of the geometry column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_GEOMETRY </em>= 1;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; city.<br>     */<br>    </em><strong>const </strong><em>CITY </em>= &#39;Baltimore&#39;;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; state.<br>     */<br>    </em><strong>const </strong><em>STATE </em>= &#39;MD&#39;;<br><br>    <em>/**<br>     * Path of the seed file relative to the `database` directory.<br>     */<br>    </em><strong>const </strong><em>DATABASE_FILE_PATH </em>= &#39;seeds/flat-files/baltimore-maryland.csv&#39;;<br><br>    <em>/**<br>     * If the file has a header row.<br>     */<br>    </em><strong>const </strong><em>HAS_HEADER_ROW </em>= <strong>true</strong>;<br><br>    <em>/**<br>     * If the neighborhood names should be converted to Title Case.<br>     */<br>    </em><strong>const </strong><em>USE_TITLE_CASE </em>= <strong>false</strong>;<br><br>    <em>/**<br>     * Run the database seeds.<br>     *<br>     * </em><strong><em>@throws </em></strong><em>\Throwable<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        // resolve the path of the seed file<br>        $file_path = database_path(<strong>self</strong>::<em>DATABASE_FILE_PATH</em>);<br><br>        // seed the neighborhoods from the flat file<br>        $this-&gt;seedFromFlatFile($file_path,<br>            <strong>self</strong>::<em>COLUMN_INDEX_NAME</em>,<br>            <strong>self</strong>::<em>COLUMN_INDEX_GEOMETRY</em>,<br>            <strong>self</strong>::<em>CITY</em>,<br>            <strong>self</strong>::<em>STATE</em>,<br>            <strong>self</strong>::<em>HAS_HEADER_ROW</em>,<br>            <strong>self</strong>::<em>USE_TITLE_CASE</em>);<br>    }<br><br>    <em>/**<br>     * Parses the geometry to a multipolygon from well-known text.<br>     *<br>     * </em><strong><em>@param </em></strong><em>mixed $geometry<br>     * </em><strong><em>@return </em></strong><em>\Grimzy\LaravelMysqlSpatial\Types\MultiPolygon<br>     */<br>    </em><strong>protected function </strong>parseGeometryToMultiPolygon($geometry): MultiPolygon<br>    {<br>        <strong>return </strong>MultiPolygon::<em>fromWKT</em>($geometry);<br>    }<br>}</pre><p>Notice how simple it was to implement a new flat file seeder because we abstracted away the logic into our base class.</p><p>Again using artisan, create our last seeder EastBatonRougeParishSeeder.</p><pre>$ php artisan make:seeder EastBatonRougeParishSeeder</pre><p>Open up the file database/seeds/EastBatonRougeParishSeeder.php and edit the contents to match below.</p><pre><strong>&lt;?php<br><br>use </strong>Grimzy\LaravelMysqlSpatial\Types\MultiPolygon;<br><strong>use </strong>Grimzy\LaravelMysqlSpatial\Types\Polygon;<br><br><strong>class </strong>EastBatonRougeParishSeeder <strong>extends </strong>BaseNeighborhoodSeeder<br>{<br>    <em>/**<br>     * Index of the name column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_NAME </em>= 2;<br><br>    <em>/**<br>     * Index of the geometry column.<br>     */<br>    </em><strong>const </strong><em>COLUMN_INDEX_GEOMETRY </em>= 1;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; city.<br>     */<br>    </em><strong>const </strong><em>CITY </em>= &#39;Baton Rouge&#39;;<br><br>    <em>/**<br>     * Name of the neighborhoods&#39; state.<br>     */<br>    </em><strong>const </strong><em>STATE </em>= &#39;LA&#39;;<br><br>    <em>/**<br>     * Path of the seed file relative to the `database` directory.<br>     */<br>    </em><strong>const </strong><em>DATABASE_FILE_PATH </em>= &#39;seeds/flat-files/east-baton-rouge-parish-louisiana.csv&#39;;<br><br>    <em>/**<br>     * If the file has a header row.<br>     */<br>    </em><strong>const </strong><em>HAS_HEADER_ROW </em>= <strong>true</strong>;<br><br>    <em>/**<br>     * If the neighborhood names should be converted to Title Case.<br>     */<br>    </em><strong>const </strong><em>USE_TITLE_CASE </em>= <strong>true</strong>;<br><br>    <em>/**<br>     * Run the database seeds.<br>     *<br>     * </em><strong><em>@throws </em></strong><em>\Throwable<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        // resolve the path of the seed file<br>        $file_path = database_path(<strong>self</strong>::<em>DATABASE_FILE_PATH</em>);<br><br>        // seed the neighborhoods from the flat file<br>        $this-&gt;seedFromFlatFile($file_path,<br>            <strong>self</strong>::<em>COLUMN_INDEX_NAME</em>,<br>            <strong>self</strong>::<em>COLUMN_INDEX_GEOMETRY</em>,<br>            <strong>self</strong>::<em>CITY</em>,<br>            <strong>self</strong>::<em>STATE</em>,<br>            <strong>self</strong>::<em>HAS_HEADER_ROW</em>,<br>            <strong>self</strong>::<em>USE_TITLE_CASE</em>);<br>    }<br><br>    <em>/**<br>     * Parses the geometry to a multipolygon from well-known text.<br>     *<br>     * </em><strong><em>@param </em></strong><em>mixed $geometry<br>     * </em><strong><em>@return </em></strong><em>\Grimzy\LaravelMysqlSpatial\Types\MultiPolygon<br>     */<br>    </em><strong>protected function </strong>parseGeometryToMultiPolygon($geometry): MultiPolygon<br>    {<br>        // parse the well-known text into a polygon<br>        $polygon = Polygon::<em>fromWKT</em>($geometry);<br><br>        // return a multipolygon containing the polygon<br>        <strong>return new </strong>MultiPolygon([$polygon]);<br>    }<br>}</pre><p>This time the implementation of the parseGeometryToMultiPolygon method is different. If you check the east-baton-rouge-parish-louisiana.csv file you’ll notice the WKT contains polygons instead of multipolygons, but the method calls for a MultiPolygon to be returned. Therefore we first parse the Polygon from WKT and then create and return a new MutliPolygon using an array containing the Polygon passed to the constructor.</p><p>Next we need to edit database/seeds/DatabaseSeeder.php to call each of our seeders. Update the file to match the contents below.</p><pre><strong>&lt;?php<br><br>use </strong>Illuminate\Database\Seeder;<br><br><strong>class </strong>DatabaseSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Seed the application&#39;s database.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        $this-&gt;call([<br>            ChicagoIllinoisNeighborhoodSeeder::<strong>class</strong>,<br>            BaltimoreMarylandSeeder::<strong>class</strong>,<br>            EastBatonRougeParishSeeder::<strong>class</strong>,<br>        ]);<br>    }<br>}</pre><p>Let’s quickly regenerate our autoload files using composer.</p><pre>$ composer dump-autoload</pre><p>Finally, let’s migrate and seed our database using an artisan command. This will create our neighborhoods table as well as seed all the neighborhoods from our flat files.</p><pre>$ php artisan migrate --seed</pre><h4>Installing the Second Package</h4><p>Use composer to require the toin0u/geocoder-laravel package we’ll be using to geocode addresses.</p><pre>$ composer require &quot;toin0u/geocoder-laravel&quot;</pre><p>While composer is running, this is a great time to get a Google API key for our project. We’ll be using Google’s Geocoding API.</p><ol><li>Go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a> and log in using a Google account.</li><li>Create a new project.</li><li>Under the APIs &amp; Services dashboard, click ENABLE APIS AND SERVICES.</li><li>Enable the Geocoding API by searching for Geocoding API, clicking on the result, and then clicking the button labeled ENABLE.</li><li>Under APIs &amp; Services go to Credentials.</li><li>Click Create and select API Key.</li><li>Copy the generated API key to your clipboard.</li></ol><p>Now we’re going to add the necessary configuration for the geocoding package we just installed.</p><p>Edit the .env environment file at the root of our project, adding the key GOOGLE_MAPS_API_KEY and pasting in the value of your API key.</p><pre>GOOGLE_MAPS_API_KEY=***************************************</pre><p>For posterity’s sake let’s also add an entry in .env.example for the same key. Remember, don’t add your API key here; this file is only a template and is checked into source control.</p><pre>GOOGLE_MAPS_API_KEY=</pre><h4>The Home Controller</h4><p>Now let’s define our routes by editing routes/web.php, deleting the existing welcome route, and replacing it with the routes below.</p><pre>Route::<em>get</em>(&#39;/&#39;, &#39;HomeController@show&#39;)-&gt;name(&#39;home.show&#39;);<br>Route::<em>post</em>(&#39;/&#39;, &#39;HomeController@submit&#39;)-&gt;name(&#39;home.submit&#39;);</pre><p>The first route, named home.show, is for displaying the home page. The second route, named home.submit, will handle the submission of addresses and return a response containing the result of the search.</p><p>Next, create a HomeController using artisan.</p><pre>$ php artisan make:controller HomeController</pre><p>Edit app/Http/Controllers/HomeController.php to match the contents below.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers;<br><br><strong>use </strong>App\Models\Neighborhood;<br><strong>use </strong>Grimzy\LaravelMysqlSpatial\Types\Point;<br><strong>use </strong>Illuminate\Http\Request;<br><br><strong>class </strong>HomeController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * The session key for storing the success message.<br>     */<br>    </em><strong>const </strong><em>SESSION_KEY_SUCCESS </em>= &#39;success&#39;;<br><br>    <em>/**<br>     * The session key for storing the error message.<br>     */<br>    </em><strong>const </strong><em>SESSION_KEY_ERROR </em>= &#39;error&#39;;<br><br>    <em>/**<br>     * The result message for an address that could not be geocoded.<br>     */<br>    </em><strong>const </strong><em>RESULT_BAD_ADDRESS </em>= &#39;Failed to find a location for that address!&#39;;<br><br>    <em>/**<br>     * The result message for an address that does not fall in any exiting Neighborhood&#39;s geometry.<br>     */<br>    </em><strong>const </strong><em>RESULT_NO_RESULTS </em>= &#39;No results for that address!&#39;;<br><br>    <em>/**<br>     * The result message prefix for a found Neighborhood.<br>     */<br>    </em><strong>const </strong><em>RESULT_NEIGHBORHOOD_PREFIX </em>= &#39;That address is in &#39;;<br><br>    <em>/**<br>     * The route name for showing the home page.<br>     */<br>    </em><strong>const </strong><em>ROUTE_NAME_SHOW_HOME </em>= &#39;home.show&#39;;<br><br>    <em>/**<br>     * Shows the home page.<br>     *<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\View\View<br>     */<br>    </em><strong>public function </strong>show()<br>    {<br>        <strong>return </strong>view(&#39;home&#39;);<br>    }<br><br>    <em>/**<br>     * Handles submission of an address and returns a redirect to the home page with success or error message.<br>     *<br>     * </em><strong><em>@param </em></strong><em>\Illuminate\Http\Request $request<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\Http\RedirectResponse<br>     */<br>    </em><strong>public function </strong>submit(Request $request)<br>    {<br>        // validate the request<br>        $this-&gt;validate($request, [<br>            &#39;address&#39; =&gt; &#39;required&#39;,<br>        ]);<br><br>        // get the given address from the request<br>        $address = $request-&gt;input(&#39;address&#39;);<br><br>        // make the geocoder<br>        $geocoder = app(&#39;geocoder&#39;);<br><br>        // geocode the address and get the first result<br>        $result = $geocoder-&gt;geocode($address)-&gt;get()-&gt;first();<br><br>        // if a result couldn&#39;t be found, redirect to the home page with a result message flashed to the session<br>        <strong>if </strong>(! $result) {<br>            <strong>return </strong>redirect(route(<strong>self</strong>::<em>ROUTE_NAME_SHOW_HOME</em>))-&gt;with(<strong>self</strong>::<em>SESSION_KEY_ERROR</em>, <strong>self</strong>::<em>RESULT_BAD_ADDRESS</em>);<br>        }<br><br>        // get the coordinates of the geocoding result<br>        $coordinates = $result-&gt;getCoordinates();<br><br>        // get the latitude of the coordinates<br>        $lat = $coordinates-&gt;getLatitude();<br><br>        // get the longitude of the coordinates<br>        $lng = $coordinates-&gt;getLongitude();<br><br>        // create a new point using the coordinates<br>        $point = <strong>new </strong>Point($lat, $lng);<br><br>        // get the first Neighborhood that has geometry containing the point<br>        $neighborhood = Neighborhood::contains(&#39;geometry&#39;, $point)-&gt;first();<br><br>        // if a Neighborhood couldn&#39;t be found, redirect to the home page with a result message flashed to the session<br>        <strong>if </strong>(! $neighborhood) {<br>            <strong>return </strong>redirect(route(<strong>self</strong>::<em>ROUTE_NAME_SHOW_HOME</em>))-&gt;with(<strong>self</strong>::<em>SESSION_KEY_ERROR</em>, <strong>self</strong>::<em>RESULT_NO_RESULTS</em>);<br>        }<br><br>        // format the result message for the found Neighborhood<br>        $message = $this-&gt;formatNeighborhoodResult($neighborhood);<br><br>        // redirect to the home page with the result message flashed to the session<br>        <strong>return </strong>redirect(route(<strong>self</strong>::<em>ROUTE_NAME_SHOW_HOME</em>))-&gt;with(<strong>self</strong>::<em>SESSION_KEY_SUCCESS</em>, $message);<br>    }<br><br>    <em>/**<br>     * Format the result message for a found neighborhood.<br>     *<br>     * </em><strong><em>@param </em></strong><em>\App\Models\Neighborhood $neighborhood<br>     * </em><strong><em>@return </em></strong><em>string<br>     */<br>    </em><strong>private function </strong>formatNeighborhoodResult(Neighborhood $neighborhood) {<br>        <strong>return self</strong>::<em>RESULT_NEIGHBORHOOD_PREFIX </em>. $neighborhood-&gt;name . &#39;, &#39; . $neighborhood-&gt;city . &#39;, &#39; . $neighborhood-&gt;state . &#39;.&#39;;<br>    }<br>}</pre><p>In this file we first define constants for the session key storing success messages, the session key storing error messages, the text for result messages, and the home.show route name.</p><p>In the show method we simply return the view named home using the Laravel <a href="https://laravel.com/docs/5.6/helpers#method-view">helper method</a> view.</p><p>The submit method accepts an argument of type Illuminate\Http\Request called $request. Laravel will automatically inject this variable containing the current request data.</p><p>First we validate the request by specifying a rule for address making the field required. The validated address is then retrieved using the input method on the $request variable. We use Laravel’s app <a href="https://laravel.com/docs/5.6/helpers#method-app">helper method</a> which uses the service container to resolve an instance of the geocoder. Using method chaining we geocode the given address and get the first result. If a result couldn’t be found for the given address we redirect the user to the home page with an error message flashed to the session.</p><p>Next we get the longitude and latitude coordinates from the result and create a new Grimzy\LaravelMysqlSpatial\Types\Point instance by passing the coordinates into the constructor.</p><p>The eloquent <a href="https://laravel.com/docs/5.6/eloquent#query-scopes">query scope</a> contains provided by the grimzy/laravel-mysql-spaital package is then used to scope the query by records with a geometry containing the point. We use the first method to get the first result. This will generate a query along the lines of:</p><pre>SELECT * FROM `neighborhoods` WHERE ST_Contains(`geometry`, ST_GeomFromText(&#39;POINT(0 0)&#39;)) LIMIT 1</pre><p>In this case &#39;POINT(0 0)&#39; is the WKT representation of our longitude and latitude (which won’t actually be 0, 0 unless our user lives in the middle of the ocean).</p><p>Notice that we are using MySQL to calculate if the the geometry contains the point. This is much faster than if we had chunked through all the records and had done the calculation in PHP.</p><p>Finally, if a resulting neighborhood containing the point couldn’t be found we return a redirect to the home page with an error message flashed to the session. Otherwise, we format the neighborhood name, city, and state into a success result message (using the formatNeighborhoodResult method) and return a redirect to the home page with the message flashed to the session.</p><h4>The Home View</h4><p>Rename the <a href="https://laravel.com/docs/5.6/blade">blade template</a> at resources/views/welcome.blade.php to resources/views/home.blade.php and open the file.</p><p>Under the &lt;!-- Styles --&gt; comment, add a link to Bootstrap’s style sheet.</p><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css&quot; integrity=&quot;sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ&quot; crossorigin=&quot;anonymous&quot;&gt;</pre><p>Next, in the .title class definition, change the font size to something smaller.</p><pre>.title {<br>    font-size: 64px;<br>}</pre><p>Just before the closing &lt;/body&gt; tag, add script tags for Bootstrap’s dependencies <a href="https://jquery.com/">jQuery</a>, <a href="https://popper.js.org/">Popper.js</a>, and Bootstrap’s minified JavaScript file.</p><pre>&lt;script src=&quot;https://code.jquery.com/jquery-3.1.1.slim.min.js&quot; integrity=&quot;sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js&quot; integrity=&quot;sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js&quot; integrity=&quot;sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><p>Because our application has no authentication, remove the entire @if (Route::has(‘login’)) directive including the contents and closing directive.</p><p>Finally, edit the contents of the &lt;div class=&quot;content&quot;&gt; div to match below.</p><pre>&lt;div class=&quot;content&quot;&gt;<br>    &lt;div class=&quot;title m-b-md&quot;&gt;<br>        Neighborhood Finder<br>    &lt;/div&gt;<br>    <strong>@if (</strong>session(&#39;success&#39;)<strong>)<br>        </strong>&lt;div class=&quot;alert alert-success&quot;&gt;<br>            {{ session(&#39;success&#39;) }}<br>        &lt;/div&gt;<br>    <strong>@elseif (</strong>session(&#39;error&#39;)<strong>)<br>        </strong>&lt;div class=&quot;alert alert-danger&quot;&gt;<br>            {{ session(&#39;error&#39;) }}<br>        &lt;/div&gt;<br>    <strong>@endif<br>    </strong>&lt;div class=&quot;col-12 text-left&quot;&gt;<br>        &lt;form class=&quot;form-horizontal&quot; method=&quot;POST&quot; action=&quot;{{ route(&#39;home.submit&#39;) }}&quot;&gt;<br>            <strong>@csrf<br>            </strong>&lt;div class=&quot;form-group{{ $errors-&gt;has(&#39;address&#39;) ? &#39; has-error&#39; : &#39;&#39; }}&quot;&gt;<br>                &lt;label for=&quot;address&quot; class=&quot;control-label&quot;&gt;Enter an address&lt;/label&gt;<br><br>                &lt;input id=&quot;address&quot; name=&quot;address&quot; type=&quot;text&quot; class=&quot;form-control&quot; required autofocus&gt;<br><br>                <strong>@if (</strong>$errors-&gt;has(&#39;address&#39;)<strong>)<br>                    </strong>&lt;span class=&quot;help-block&quot;&gt;<br>                        &lt;strong&gt;{{ $errors-&gt;first(&#39;address&#39;) }}&lt;/strong&gt;<br>                    &lt;/span&gt;<br>                <strong>@endif<br>            </strong>&lt;/div&gt;<br>            &lt;div class=&quot;form-group text-right&quot;&gt;<br>                &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;<br>                    Submit<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Here we use the blade directive @if to check if there’s a message in the success key of the current session. If there is one, we display an alert to the user containing the message. If there isn’t one, we use the blade directive @elseif to check if there’s a message in the error key of the current session, again displaying it to the user if it exists.</p><p>Next we define a form with an action specifying our submission route using the route <a href="https://laravel.com/docs/5.6/helpers#method-route">helper method</a>. The @crsf blade directive is used to generate a <a href="https://laravel.com/docs/5.6/csrf">Cross-Site Request Forgery</a> field and token. If the $errors message bag contains an entry for address we add the has-error class to the form group div and display the error in a help block.</p><h3>Conclusion</h3><p>That’s it! Open the project in your browser and try out some different addresses! The address will be geocoded and a neighborhood will be returned if any neighborhoods in the database have a boundary containing the address’s coordinates. If no address coordinates or neighborhood could be found, an error message stating such will be returned.</p><p>Try some of these addresses:</p><pre>1558 N Damen Ave, Chicago, IL 60622</pre><pre>1001 E Fayette St, Baltimore, MD 21202</pre><pre>201 Community College Dr, Baton Rouge, LA 70806</pre><pre>123 Fake St, Nowhere</pre><pre>Your Address</pre><h4>Additional Resources</h4><p>For additional data sources I encourage you to check out this <a href="https://www.forbes.com/sites/metabrown/2017/06/30/quick-links-to-municipal-open-data-portals-for-85-us-cities">Forbes article</a> as well as <a href="https://opendatainception.io/">Open Data Inception</a>.</p><p>You can view the source code for this project <a href="https://github.com/bricehartmann/laravel-neighborhood-finder">on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94502dc74d55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a User-Based Task List Application in Laravel]]></title>
            <link>https://medium.com/@brice_hartmann/building-a-user-based-task-list-application-in-laravel-eff4a07e2688?source=rss-6fd5158e5434------2</link>
            <guid isPermaLink="false">https://medium.com/p/eff4a07e2688</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Brice Hartmann]]></dc:creator>
            <pubDate>Mon, 09 Jul 2018 07:10:08 GMT</pubDate>
            <atom:updated>2018-11-14T18:57:36.689Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>In this article we will be building a task list application in <a href="https://laravel.com/docs/5.7">Laravel 5.7</a> complete with a paginated list of tasks per user account, user registration, and password resets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQ1_IUiS-gAj5JirO9u_5A.png" /><figcaption>screenshot of the application we are building</figcaption></figure><p>There are a few things you should be familiar with already in order to get the most out of this article.</p><ul><li>You should be familiar with PHP. I recommend <a href="https://www.phptherightway.com/">PHP: The Right Way</a> for a quick start.</li><li>You should be comfortable using the terminal. If you’re on Windows I recommend installing <a href="https://gitforwindows.org/">git for Windows</a>.</li><li>You have a Laravel development environment set up. I recommend using the Vagrant box <a href="https://laravel.com/docs/5.7/homestead">Homestead</a>.</li></ul><p>To begin, let’s define the basic functionality of our application:</p><ul><li>a user can register for an account</li><li>a user can reset their password via an email link</li><li>a user can log in to their account</li><li>tasks are private to a user account</li><li>a user can create new tasks</li><li>a user can see a paginated list of their tasks with completed tasks at the end</li><li>a user can mark a task as complete</li><li>a user can log out of their account</li></ul><p>Below is a basic schema of our application’s database. A data type in bold means not nullable. PK stands for Primary Key and FK stands for Foreign Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etcvNbdKQblcsqLu5YDk6Q.png" /><figcaption>basic schema of our application’s database</figcaption></figure><p><em>Note that we won’t be covering email verification in this article. For more information on using the </em><em>email_verified_at column, check out the </em><a href="https://laravel.com/docs/5.7/verification"><em>documentation</em></a><em>.</em></p><h3>Environment Configuration</h3><p>Let’s get started by configuring Homestead and provisioning the Vagrant box.</p><p>If you’re not using Homestead, skip this part and set up your local environment for a new Laravel project as needed.</p><p>Edit your Homestead.yaml configuration file and add an entry under sites for our project. If you plan on creating the project in a directory other than the vagrant user’s home directory, be sure to update the file path to where you’ll be creating the project.</p><pre>- map: task-app.test  <br>  to: /home/vagrant/task-app/public</pre><p>We also need to edit our hosts file and add the domain of our local site. On Max and Linux this is located at /etc/hosts and on Windows at C:\Windows\System32\drivers\etc\hosts.</p><p>Add the following entry to your hosts file:</p><pre>192.168.10.10 task-app.test</pre><p>Note that the local IP address 192.168.10.10 matches the configured IP address at the top of our Homestead.yaml file.</p><p>Now we need to provision our Vagrant box so Homestead can serve our newly configured site.</p><pre>$ vagrant reload --provision</pre><p>After Vagrant is finished provisioning the virtual machine ssh into the box.</p><pre>$ vagrant ssh</pre><h3>Project Setup</h3><p>Now it’s time to create our project using <a href="https://getcomposer.org/">Composer</a>, a dependency manager for PHP. This will generate a new Laravel application using the latest stable release into the directory task-app.</p><pre>$ composer create-project --prefer-dist laravel/laravel task-app</pre><p>Alternatively, you can also create the project using the <a href="https://laravel.com/docs/5.7/installation#installing-laravel">Laravel Installer</a>. Either way works and the result will be the same.</p><pre>$ laravel new task-app</pre><p>Before we start coding let’s update our <a href="https://laravel.com/docs/5.7/configuration">Environment Configuration</a> with our application’s name and URL. Edit the top of the .env file at the root of the project directory with the updated APP_NAME and APP_URL.</p><pre>APP_NAME=&quot;Task App&quot;<br>APP_ENV=local<br>APP_KEY=base64:YOUR_APP_KEY<br>APP_DEBUG=true<br>APP_URL=http://task-app.test</pre><p>A few lines down in the same file, enter your mailtrap credentials. <a href="https://mailtrap.io/">Mailtrap.io</a> is a great way to test emails locally without needing an actual email server (and without actually sending emails). It works by acting like an email server and showing you an outbox of emails that <em>would </em>have been sent.</p><p>Configure your .env file with your mailtrap username and password, optionally specifying the value tls for MAIL_ENCRYPTION to use the <a href="https://en.wikipedia.org/wiki/Transport_Layer_Security">TLS protocol</a> when sending emails. Let’s also specify a MAIL_FROM_NAME and MAIL_FROM_ADDRESS for sending emails. Laravel looks for these environment variables out of the box.</p><pre>MAIL_DRIVER=smtp<br>MAIL_HOST=smtp.mailtrap.io<br>MAIL_PORT=2525<br>MAIL_USERNAME=**************<br>MAIL_PASSWORD=**************<br>MAIL_ENCRYPTION=tls<br>MAIL_FROM_NAME=&quot;Task App&quot;<br>MAIL_FROM_ADDRESS=no-reply@task-app.test</pre><p>As a good practice, let’s keep the .env.example file up to date with our configuration. Open up the file at the root of the project and add entries for both MAIL_FROM_NAME and MAIL_FROM_ADDRESS, underneath the entry for MAIL_ENCRYPTION.</p><pre>MAIL_FROM_NAME=<br>MAIL_FROM_ADDRESS=</pre><p>Great! Next let’s touch up the welcome view by editing the resources/views/welcome.blade.php file.</p><p>Edit the contents of the title tag to contain {{ config(&#39;app.name&#39;) }}. This will insert the value of APP_NAME from our environment file. The string &#39;app.name&#39; tells the config() helper function to look in the file config/app.php for an array key name and return the value. Take a look at the contents of the config directory to learn more about Laravel configuration.</p><p>Edit the title tag to look like:</p><pre>&lt;title&gt;{{ config(&#39;app.name&#39;) }}&lt;/title&gt;</pre><p>Additionally in the same view, edit the div with class=&quot;content&quot; by removing the links and editing the <a href="https://laravel.com/docs/5.7/blade">blade template</a> to display our application name.</p><pre>&lt;div class=&quot;content&quot;&gt;<br>    &lt;div class=&quot;title m-b-md&quot;&gt;<br>        {{ config(&#39;app.name&#39;) }}<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>You should now be able to navigate to task-app.test in your browser and see the title of our application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Gt_em65nnS9j8lGg958R5A.png" /></figure><h3>Some Personal Preferences</h3><p>Now for some personal preferences; things I like to do at the beginning of every project.</p><ol><li>Eloquent models go in the app/Models directory. This keeps our project structure tidy even if we have dozens of models (as opposed to putting them in the app directory which Laravel does by default).</li><li>Password encryption is handled by a <a href="https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator">mutator</a> on the User model. By using a mutator to encrypt the password we centralize where encryption happens, making it easier to swap out the implementation later if we desire. We also never have to remember to encrypt the password when creating a new User , just set the password attribute and the mutator takes care of the rest!</li><li>Give the password_resets table a primary key. In my opinion having a primary key on every table is a best practice so let’s add one to the password_resets migration Laravel provides.</li></ol><p>Let’s start by creating a new directory at app/Models.</p><pre>$ mkdir app/Models</pre><p>Move the User model into the new directory.</p><pre>$ mv app/User.php app/Models/</pre><p>Next let’s open up app/Models/User.php. Start by updating the namespace at the top to match our directory structure.</p><pre><strong>namespace </strong>App\Models;</pre><p>While we’re editing this file let’s add the mutator method which encrypts the given value before setting it on the password attribute. The method naming convention setSomeAttribute where Some is the name of your attribute will register a mutator with Laravel.</p><pre><em>/**<br> * Set and encrypt the password attribute.<br> *<br> * </em><strong><em>@param </em></strong><em>$value<br> */<br></em><strong>public function </strong>setPasswordAttribute($value)<br>{<br>    $this-&gt;attributes[&#39;password&#39;] = bcrypt($value);<br>}</pre><p>As mentioned earlier, we no longer need to encrypt the value before assigning a password, the mutator will do this for us. With that in mind, there are a couple of places we need to update in order for things to work properly.</p><p>Open up the UserFactory at database/factories/UserFactory and edit the contents to match below. We need to update the namespace where the User class is referenced as well as change where the password is being set to no longer be encrypted (as the mutator will do this already).</p><pre>$factory-&gt;define(App\Models\User::<strong>class</strong>, <strong>function </strong>(Faker $faker) {<br>    <strong>return </strong>[<br>        &#39;name&#39; =&gt; $faker-&gt;name,<br>        &#39;email&#39; =&gt; $faker-&gt;unique()-&gt;safeEmail,<br>        &#39;email_verified_at&#39; =&gt; now(),<br>        &#39;password&#39; =&gt; &#39;secret&#39;,<br>        &#39;remember_token&#39; =&gt; str_random(10),<br>    ];<br>});</pre><p>I like to use the password secret for testing but feel free to update the string literal with any password you like.</p><p>Next, update where the User class is referenced in config/auth.php with the model’s new namespace.</p><pre>&#39;providers&#39; =&gt; [<br>    &#39;users&#39; =&gt; [<br>        &#39;driver&#39; =&gt; &#39;eloquent&#39;,<br>        &#39;model&#39; =&gt; App\Models\User::<strong>class</strong>,<br>    ],</pre><pre>    // &#39;users&#39; =&gt; [<br>    //     &#39;driver&#39; =&gt; &#39;database&#39;,<br>    //     &#39;table&#39; =&gt; &#39;users&#39;,<br>    // ],<br>],</pre><p>Finally, add an auto-incrementing id column to the password_resets table using the increments <a href="https://laravel.com/api/5.7/Illuminate/Database/Schema/Blueprint.html#method_increments">method</a>. Update the up method in database/migrations/*_create_password_resets_table.php to match below. Notes the * in your file name will be replaced with a date and time.</p><pre><em>/**<br> * Run the migrations.<br> *<br> * </em><strong><em>@return </em></strong><em>void<br> */<br></em><strong>public function </strong>up()<br>{<br>    Schema::<em>create</em>(&#39;password_resets&#39;, <strong>function </strong>(Blueprint $table) {<br>        $table-&gt;increments(&#39;id&#39;);<br>        $table-&gt;string(&#39;email&#39;)-&gt;index();<br>        $table-&gt;string(&#39;token&#39;);<br>        $table-&gt;timestamp(&#39;created_at&#39;)-&gt;nullable();<br>    });<br>}</pre><h3>Authentication</h3><p>We’re ready to generate scaffolding for Laravel’s <a href="https://laravel.com/docs/5.7/authentication">authentication system</a>! We can do this with a convenient artisan command.</p><pre>$ php artisan make:auth</pre><p>This will do five things for us:</p><ol><li>Modify our routes/web.php file adding the statementAuth::routes();</li><li>Create a HomeController at app/Http/Controllers/HomeController.php</li><li>Create an application layout (blade template) at resources/views/layouts/app.blade.php</li><li>Create a home view (blade template) at resources/views/home.blade.php</li><li>Create authentication views (blade templates) for logging in, resetting passwords, and registering in resources/views/auth/</li></ol><h4>Updates to Scaffolding</h4><p>There are a few places we need to update so the scaffolding works with our project. Open up the RegisterController at app/Http/Controllers/RegisterController.php.</p><p>At the top of the file, update the use statement to reflect the namespace of our User model.</p><pre>use App\Models\User;</pre><p>Next update the docblock on the create method. Also update where the password is set to not encrypt the password, as our mutator on the User model will handle this for us.</p><pre><em>/**<br> * Create a new user instance after a valid registration.<br> *<br> * </em><strong><em>@param  </em></strong><em>array  $data<br> * </em><strong><em>@return </em></strong><em>\App\Models\User<br> */<br></em><strong>protected function </strong>create(<strong>array </strong>$data)<br>{<br>    <strong>return </strong>User::<em>create</em>([<br>        &#39;name&#39; =&gt; $data[&#39;name&#39;],<br>        &#39;email&#39; =&gt; $data[&#39;email&#39;],<br>        &#39;password&#39; =&gt; $data[&#39;password&#39;],<br>    ]);<br>}</pre><p>Note we no longer need the use Illuminate\Support\Facades\Hash; at top of the file.</p><p>Moving on, open up the ResetPasswordController at app/Http/Controllers/ResetPasswordController.php and notice the controller uses the Illuminate\Foundation\Auth\ResetsPasswords trait. If you look at the resetPassword method on this trait you’ll see we <a href="https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Auth/ResetsPasswords.php#L105">would be encrypting our password twice</a> because the mutator on our User model will also encrypt the password. To prevent this double encryption let’s override the resetPassword method in our ResetPassword controller.</p><pre><em>/**<br> * Reset the given user&#39;s password.<br> *<br> * </em><strong><em>@param  </em></strong><em>\Illuminate\Contracts\Auth\CanResetPassword  $user<br> * </em><strong><em>@param  </em></strong><em>string $password<br> * </em><strong><em>@return </em></strong><em>void<br> */<br></em><strong>protected function </strong>resetPassword($user, $password)<br>{<br>    $user-&gt;password = $password;</pre><pre>    $user-&gt;setRememberToken(str_random(60));</pre><pre>    $user-&gt;save();</pre><pre>    event(<strong>new </strong>PasswordReset($user));</pre><pre>    $this-&gt;guard()-&gt;login($user);<br>}</pre><p>Be sure to add use Illuminate\Auth\Events\PasswordReset; at the top of the file.</p><h4>Test Users</h4><p>To create some test users for our application let’s create a <a href="https://laravel.com/docs/5.7/seeding">seeder</a> called UsersTableSeeder using an artisan command.</p><pre>$ php artisan make:seeder UsersTableSeeder</pre><p>Open the generated seeder at database/seeds/UsersTableSeeder.php and edit the contents to match below.</p><pre><strong>&lt;?php</strong></pre><pre><strong>use </strong>App\Models\User;<br><strong>use </strong>Illuminate\Database\Seeder;</pre><pre><strong>class </strong>UsersTableSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Run the database seeds.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        // create a test user<br>        factory(User::<strong>class</strong>)-&gt;create([<br>            &#39;name&#39; =&gt; &#39;Test User&#39;,<br>            &#39;email&#39; =&gt; &#39;user@example.com&#39;<br>        ]);<br>        <br>        // create 50 random test users<br>        factory(User::<strong>class</strong>, 50)-&gt;create();<br>    }<br>}</pre><p>Notice how we’re using <a href="https://laravel.com/docs/5.7/seeding#using-model-factories">factories</a> to create our test users. The first statement in the run method creates a test user and modifies the name and email attributes to something we know. The second statement creates 50 random test users using the default UserFactory.</p><p>Next open database/seeds/DatabaseSeeder.php and modify the run method to run our new seeder. Notice how the call method is accepting an array of seeder classes. This will make it easy in the future to simply add another seeder to the array.</p><pre><strong>&lt;?php</strong></pre><pre><strong>use </strong>Illuminate\Database\Seeder;</pre><pre><strong>class </strong>DatabaseSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Seed the application&#39;s database.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        $this-&gt;call([<br>            UsersTableSeeder::<strong>class</strong>,<br>        ]);<br>    }<br>}</pre><p>Before we can migrate and seed our database we need to do one more thing: we need to regenerate the autoload classmap used by Composer to locate our files.</p><pre>$ composer dump-autoload</pre><p>Finally, let’s migrate and seed our database using the migrate <a href="https://laravel.com/docs/5.7/migrations#running-migrations">artisan command</a> in combination with the --seed flag.</p><pre>$ php artisan migrate --seed</pre><h4>Testing Authentication</h4><p>Before we get to more coding, let’s quickly test the functionality of our application to verify our changes.</p><p>Refresh task-app.test in your browser to see a new menu in the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*1tD1PjTndEIOTYBpLWVd6A.png" /></figure><p>This appeared because of the conditional statement in resources/views/welcome.blade.</p><pre><strong>@if (</strong>Route::<em>has</em>(&#39;login&#39;)<strong>)<br>    </strong>&lt;div class=&quot;top-right links&quot;&gt;<br>        <strong>@auth<br>            </strong>&lt;a href=&quot;{{ url(https://medium.com/&#39;/home&#39;) }}&quot;&gt;Home&lt;/a&gt;<br>        <strong>@else<br>            </strong>&lt;a href=&quot;{{ route(&#39;login&#39;) }}&quot;&gt;Login&lt;/a&gt;<br>            &lt;a href=&quot;{{ route(&#39;register&#39;) }}&quot;&gt;Register&lt;/a&gt;<br>        <strong>@endauth<br>    </strong>&lt;/div&gt;<br><strong>@endif</strong></pre><p>If the route definition has a route named login, render the div contained by the directive. Inside the directive is another directive @auth which acts just like the directive @if (Auth::check()). If the user is authenticated, display a link for the home page. Otherwise, display links for logging in and registering.</p><p>Click on “LOGIN”.</p><p>Fill in the credentials for our test user and click on “Login”. Remember that unless you changed it to something else, the password we set in our UserFactory is secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*HRyHeoRxwbM2yGM1OMEbeg.png" /></figure><p>You will be redirected to the home page for our test user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lBQ3Ht6r97OW12_STpn5aA.png" /></figure><p>Using the menu in the top right, log out of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*HjP8ZXozdFyTPEqDLAJ0XQ.png" /></figure><p>Next let’s test user registration. Click on “REGISTER” in the menu in the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*1tD1PjTndEIOTYBpLWVd6A.png" /></figure><p>Register for a new user account using any name, email address, and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*IjWl5BFll1Huzv0fw_sbUA.png" /></figure><p>You will be logged in and redirected to the home page for your new user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*lBQ3Ht6r97OW12_STpn5aA.png" /></figure><p>Again, log out of the application using the menu in the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*lubS1p9Xnv_nzlgnScv69Q.png" /></figure><p>Now let’s test the forgot password functionality of our application.</p><p>Click on “LOGIN” in the top right menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*XT5G5JAT6ZAJ3bsV5V5xhw.png" /></figure><p>This time, click on the link “Forgot Your Password?”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*FGxflM-4vXXz5cDEaJj2GA.png" /></figure><p>Enter the email address for our test user user@example.com and click “Send Password Reset Link”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*ZuwYuyjEypZNxOXLbXgveA.png" /></figure><p>You will receive a confirmation message on the next page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*U8sjKDC_h0dAy94ZuLzfqw.png" /></figure><p>Now go to your <a href="https://mailtrap.io/">mailtrap account</a> where you will be able to see the email that would have been sent. To learn about customizing this email, read the <a href="https://laravel.com/docs/5.7/mail">Laravel documentation</a> on mail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*9bpW9wVbK0kmSVtHqjLv2g.png" /></figure><p>Note how the domain used in the password reset link is the domain we configured for the APP_URL environment variable. Laravel uses this environment variable when generating URLs for the application.</p><p>Click the “Reset Password” button in the email and you will be directed to a reset password form in our application at the task-app.test domain.</p><p>Enter user@exmaple.com for the email address and enter and confirm a new password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*Nv1CdZjs9K1sv2yLcHEe4Q.png" /></figure><p>Click on “Reset Password” and you’ll receive a confirmation message on the next page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*wbprBUBNI3ZKB2hTJeZ3Sw.png" /></figure><p>Just like that, we have a full authentication system complete with logging in and out, user registration, and password resets! I encourage you to read more about Laravel authentication in the <a href="https://laravel.com/docs/5.7/authentication">documentation</a>.</p><h3>Implementing Tasks</h3><p>With our authentication system in place it’s time to implement the functionality of a task list for each user account.</p><h4>Model, Migration, and Test Data</h4><p>First let’s generate a Task model and database migration using an artisan command. Note how we can specify the namespace of our new model by escaping backslashes. This namespace will be prefixed with App.</p><pre>$ php artisan make:model Models\\Task --migration</pre><p>Open up the generated migration at database/migrations/*_create_tasks_table.php and edit the contents to match below.</p><p>We’ll be adding a user_id foreign key to the users table, a string named title for each task, a boolean flag is_complete for tracking if each task is complete, and timestamps for tracking when each task is created and updated, respectively. The timestamps are added using the timestamps method, which creates two nullable timestamps named created_at and updated_at.</p><pre><strong>&lt;?php</strong></pre><pre><strong>use </strong>Illuminate\Support\Facades\Schema;<br><strong>use </strong>Illuminate\Database\Schema\Blueprint;<br><strong>use </strong>Illuminate\Database\Migrations\Migration;</pre><pre><strong>class </strong>CreateTasksTable <strong>extends </strong>Migration<br>{<br>    <em>/**<br>     * Run the migrations.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>up()<br>    {<br>        Schema::<em>create</em>(&#39;tasks&#39;, <strong>function </strong>(Blueprint $table) {<br>            $table-&gt;increments(&#39;id&#39;);<br>            $table-&gt;unsignedInteger(&#39;user_id&#39;);<br>            $table-&gt;string(&#39;title&#39;);<br>            $table-&gt;boolean(&#39;is_complete&#39;);<br>            $table-&gt;timestamps();</pre><pre>            $table<br>                -&gt;foreign(&#39;user_id&#39;)<br>                -&gt;references(&#39;id&#39;)<br>                -&gt;on(&#39;users&#39;);<br>        });<br>    }</pre><pre>    <em>/**<br>     * Reverse the migrations.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>down()<br>    {<br>        Schema::<em>dropIfExists</em>(&#39;tasks&#39;);<br>    }<br>}</pre><p>Next update our Task model by editing the contents of app/Models/Task.php.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Models;<br><br><strong>use </strong>Illuminate\Database\Eloquent\Model;<br><br><strong>class </strong>Task <strong>extends </strong>Model<br>{<br>    <em>/**<br>     * The attributes that should be cast to native types.<br>     *<br>     * </em><strong><em>@var </em></strong><em>array<br>     */<br>    </em><strong>protected </strong>$casts = [<br>        &#39;is_complete&#39; =&gt; &#39;boolean&#39;,<br>    ];<br><br>    <em>/**<br>     * The attributes that are mass assignable.<br>     *<br>     * </em><strong><em>@var </em></strong><em>array<br>     */<br>    </em><strong>protected </strong>$fillable = [<br>        &#39;title&#39;,<br>        &#39;is_complete&#39;,<br>    ];<br><br>    <em>/**<br>     * The relationship to the owning user.<br>     *<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\Database\Eloquent\Relations\BelongsTo<br>     */<br>    </em><strong>public function </strong>user()<br>    {<br>        <strong>return </strong>$this-&gt;belongsTo(User::<strong>class</strong>);<br>    }<br>}</pre><p>The $casts array tells Laravel to automatically cast the is_complete attribute to a boolean type.</p><p>The $fillable array tells Laravel we want to be able to “fill” the title and is_complete attributes with <a href="https://laravel.com/docs/5.7/eloquent#mass-assignment">mass assignment</a> arrays using methods such as create, fill, or the model’s constructor.</p><p>The user method on the model defines a “belongs to” <a href="https://laravel.com/docs/5.7/eloquent-relationships#one-to-many-inverse">relationship</a> to the User model. This is the user that owns the task.</p><p>Let’s add the inverse relationship to our User model by opening up app/Models/Users.php and adding a tasks method which defines a “has many” relationship to the Task model.</p><pre><em>/**<br> * The relationship to the user&#39;s tasks.<br> *<br> * </em><strong><em>@return </em></strong><em>\Illuminate\Database\Eloquent\Relations\HasMany<br> */<br></em><strong>public function </strong>tasks()<br>{<br>    <strong>return </strong>$this-&gt;hasMany(Task::<strong>class</strong>);<br>}</pre><p>In order to generate some test data for our application let’s define a TaskFactory. Create a file at database/factories/TaskFactory.php and edit the contents to match below.</p><pre><strong>&lt;?php</strong></pre><pre><strong>use </strong>Faker\Generator <strong>as </strong>Faker;</pre><pre>$factory-&gt;define(App\Models\Task::<strong>class</strong>, <strong>function </strong>(Faker $faker) {<br>    <strong>return </strong>[<br>        &#39;title&#39; =&gt; $faker-&gt;sentence,<br>        &#39;is_complete&#39; =&gt; $faker-&gt;boolean,<br>    ];<br>});</pre><p>With this definition we can use the factory method to generate random instances of our Task model, using <a href="https://github.com/fzaninotto/Faker">Faker</a> for random sentences and boolean values.</p><p>Next generate a TasksTableSeeder using the artisan command make:seeder.</p><pre>$ php artisan make:seeder TasksTableSeeder</pre><p>Edit the generated file at database/seeds/TasksTableSeeder.php and modify its contents to create 10–20 tasks for each user.</p><pre><strong>&lt;?php<br><br>use </strong>App\Models\Task;<br><strong>use </strong>App\Models\User;<br><strong>use </strong>Illuminate\Database\Seeder;<br><br><strong>class </strong>TasksTableSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Run the database seeds.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        // get all users<br>        $users = User::<em>all</em>();<br><br>        // loop through each user<br>        <strong>foreach </strong>($users <strong>as </strong>$user) {<br>            // determine how many tasks to create for the user<br>            $limit = random_int(10, 20);<br><br>            // create a new task until the limit is hit<br>            <strong>for </strong>($i = 0; $i &lt; $limit; $i++) {<br>                // make a new random task<br>                $task = factory(Task::<strong>class</strong>)-&gt;make();<br>                <br>                // associate the task to the user<br>                $task-&gt;user()-&gt;associate($user);<br>                <br>                // save the task<br>                $task-&gt;save();<br>            }<br>        }<br>    }<br>}</pre><p>To seed our tasks table we first get all users in the database. Next we loop through each user and determine a random number of tasks (between 10 and 20) to create for the user. On each iteration of the for loop until the limit is reached we use the factory <a href="https://laravel.com/docs/5.7/helpers#method-factory">helper method</a> to make a new instance of a Task, associate the task with the user, and save the task.</p><p>Now let’s migrate our database using the migrate artisan command to create our tasks table.</p><pre>$ php artisan migrate</pre><p>Let’s also run our TaskTableSeeder using the db:seed artisan command with the --class flag.</p><pre>$ php artisan db:seed --class TasksTableSeeder</pre><p>As a sanity check let’s fire up <a href="https://laravel-news.com/laravel-tinker">Tinker</a> and retrieve the tasks associated with the first user in the database.</p><pre>$ php artisan tinker</pre><pre>&gt;&gt;&gt; App\Models\User::first()-&gt;tasks</pre><p>Tinker will display the collection of Task models associated with the first user. Exit Tinker by typing exit.</p><p>Finally, edit database/seeds/DatabaseSeeder.php and add our TasksTableSeeder to the array passed to the call method. This way any time our database is seeded using the db:seed or migrate --seed commands our new seeder will be included.</p><pre><strong>&lt;?php</strong></pre><pre><strong>use </strong>Illuminate\Database\Seeder;</pre><pre><strong>class </strong>DatabaseSeeder <strong>extends </strong>Seeder<br>{<br>    <em>/**<br>     * Seed the application&#39;s database.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>run()<br>    {<br>        $this-&gt;call([<br>            UsersTableSeeder::<strong>class</strong>,<br>            TasksTableSeeder::<strong>class</strong>,<br>        ]);<br>    }<br>}</pre><h4>Routes, Controller, and Policy</h4><p>Next let’s get to work on our controllers. Delete the file at app/Http/Controllers/HomeController.php as we don’t need it anymore.</p><p>Edit app/Http/Controllers/Auth/LoginController.php and update the $redirectTo property to redirect to the route /tasks.</p><pre><em>/**<br> * Where to redirect users after login.<br> *<br> * </em><strong><em>@var </em></strong><em>string<br> */<br></em><strong>protected </strong>$redirectTo = &#39;/tasks&#39;;</pre><p>Make the same change in both app/Http/Controllers/Auth/RegisterController.php and app/Http/Controller/Auth/ResetPasswordController.php.</p><p>Let’s define the <a href="https://laravel.com/docs/5.7/controllers#restful-partial-resource-routes">resource routes</a> in routes/web.php as well as remove the entry for the home controller. Edit routes/web.php to match the contents below.</p><pre><strong>&lt;?php<br><br></strong>Route::<em>get</em>(&#39;/&#39;, <strong>function </strong>() {<br>    <strong>return </strong>view(&#39;welcome&#39;);<br>});<br><br>Auth::<em>routes</em>();<br><br>Route::<em>middleware</em>([&#39;auth&#39;])-&gt;group(<strong>function</strong>() {<br>    Route::<em>resource</em>(&#39;tasks&#39;, &#39;TaskController&#39;, [<br>        &#39;only&#39; =&gt; [<br>            &#39;index&#39;, &#39;store&#39;, &#39;update&#39;<br>        ]<br>    ]);<br><br>});</pre><p>Notice how we’re using the auth middleware for our route group. This will ensure only authenticated users can access the routes in the group. Inside the group we’re defining three routes to be handled by a TaskController:</p><ul><li>GET /tasks (index)</li><li>POST /tasks (store)</li><li>PATCH /tasks/{task} (update)</li></ul><p>Now that we’ve defined the /tasks route, let’s quickly edit the resources/views/welcome.blade.php file to link to our new route instead of /home.</p><p>Change the line &lt;a href=&quot;{{ url(https://medium.com/&#39;/home&#39;) }}&quot;&gt;Home&lt;/a&gt; to the following:</p><pre>&lt;a href=&quot;{{ url(https://medium.com/&#39;/tasks&#39;) }}&quot;&gt;Tasks&lt;/a&gt;</pre><p>Next let’s generate a TaskController using the artisan command make:controller.</p><pre>$ php artisan make:controller TaskController</pre><p>Open up the generated file at app/Http/Controllers/TaskController.php and add the methods index, store, and update.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers;<br><br><strong>use </strong>App\Models\Task;<br><strong>use </strong>Illuminate\Http\Request;<br><strong>use </strong>Illuminate\Support\Facades\Auth;<br><br><strong>class </strong>TaskController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * Paginate the authenticated user&#39;s tasks.<br>     *<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\View\View<br>     */<br>    </em><strong>public function </strong>index()<br>    {<br>        // paginate the authorized user&#39;s tasks with 5 per page<br>        $tasks = Auth::<em>user</em>()<br>            -&gt;tasks()<br>            -&gt;orderBy(&#39;is_complete&#39;)<br>            -&gt;orderByDesc(&#39;created_at&#39;)<br>            -&gt;paginate(5);<br><br>        // return task index view with paginated tasks<br>        <strong>return </strong>view(&#39;tasks&#39;, [<br>            &#39;tasks&#39; =&gt; $tasks<br>        ]);<br>    }<br><br>    <em>/**<br>     * Store a new incomplete task for the authenticated user.<br>     *<br>     * </em><strong><em>@param </em></strong><em>\Illuminate\Http\Request $request<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\Http\RedirectResponse<br>     */<br>    </em><strong>public function </strong>store(Request $request)<br>    {<br>        // validate the given request<br>        $data = $this-&gt;validate($request, [<br>            &#39;title&#39; =&gt; &#39;required|string|max:255&#39;,<br>        ]);<br><br>        // create a new incomplete task with the given title<br>        Auth::<em>user</em>()-&gt;tasks()-&gt;create([<br>            &#39;title&#39; =&gt; $data[&#39;title&#39;],<br>            &#39;is_complete&#39; =&gt; <strong>false</strong>,<br>        ]);<br><br>        // flash a success message to the session<br>        session()-&gt;flash(&#39;status&#39;, &#39;Task Created!&#39;);<br><br>        // redirect to tasks index<br>        <strong>return </strong>redirect(&#39;/tasks&#39;);<br>    }<br><br>    <em>/**<br>     * Mark the given task as complete and redirect to tasks index.<br>     *<br>     * </em><strong><em>@param </em></strong><em>\App\Models\Task $task<br>     * </em><strong><em>@return </em></strong><em>\Illuminate\Routing\Redirector<br>     * </em><strong><em>@throws </em></strong><em>\Illuminate\Auth\Access\AuthorizationException<br>     */<br>    </em><strong>public function </strong>update(Task $task)<br>    {<br>        // check if the authenticated user can complete the task<br>        $this-&gt;authorize(&#39;complete&#39;, $task);<br><br>        // mark the task as complete and save it<br>        $task-&gt;is_complete = <strong>true</strong>;<br>        $task-&gt;save();<br><br>        // flash a success message to the session<br>        session()-&gt;flash(&#39;status&#39;, &#39;Task Completed!&#39;);<br><br>        // redirect to tasks index<br>        <strong>return </strong>redirect(&#39;/tasks&#39;);<br>    }<br>}</pre><p>The index method paginates the authenticated user’s tasks, 5 per page, and returns the tasks view with the$task paginator as data for the view.</p><p>The store method validates the given request, creates a new incomplete task associated with the authenticated user, flashes a success message to the session, and redirects the user to the tasks index. Data <a href="https://laravel.com/docs/5.7/session#flash-data">flashed to the session</a> is only stored for the next request.</p><p>The update method asserts the authenticated user is authorized to complete the given task, marks the task as complete, flashes a success message to the session, and redirects the user to the tasks index.</p><p>In order for the authorize method to check if the authenticated user is authorized to complete the task, we need to create a TaskPolicy.</p><p>Once again, we can do this with a convenient artisan command.</p><pre>$ php artisan make:policy TaskPolicy</pre><p>Edit the created file at app/Policies/TaskPolicy.php to match below.</p><pre><strong>&lt;?php</strong></pre><pre><strong>namespace </strong>App\Policies;</pre><pre><strong>use </strong>App\Models\Task;<br><strong>use </strong>App\Models\User;<br><strong>use </strong>Illuminate\Auth\Access\HandlesAuthorization;</pre><pre><strong>class </strong>TaskPolicy<br>{<br>    <strong>use </strong>HandlesAuthorization;</pre><pre>    <em>/**<br>     * Determine if a user can complete a task.<br>     *<br>     * </em><strong><em>@param </em></strong><em>\App\Models\User $user<br>     * </em><strong><em>@param </em></strong><em>\App\Models\Task $task<br>     * </em><strong><em>@return </em></strong><em>bool<br>     */<br>    </em><strong>public function </strong>complete(User $user, Task $task)<br>    {<br>        <strong>return </strong>$user-&gt;is($task-&gt;user);<br>    }<br>}</pre><p>Here the complete method name matches the string literal passed to the authorize method in the update action method of our Task controller. The first parameter $user will be the authenticated user. The second parameter $task is the task the authenticated user is trying to modify. We return a boolean indicating if the $user is the same user that owns the $task.</p><p>In order for Laravel to associate our policy with our Task model we need to add an entry to the $policies array in app/Providers/AuthServiceProvider.php. Open that file and edit the contents to match below.</p><pre><strong>&lt;?php</strong></pre><pre><strong>namespace </strong>App\Providers;</pre><pre><strong>use </strong>App\Models\Task;<br><strong>use </strong>App\Policies\TaskPolicy;<br><strong>use </strong>Illuminate\Foundation\Support\Providers\AuthServiceProvider <strong>as </strong>ServiceProvider;</pre><pre><strong>class </strong>AuthServiceProvider <strong>extends </strong>ServiceProvider<br>{<br>    <em>/**<br>     * The policy mappings for the application.<br>     *<br>     * </em><strong><em>@var </em></strong><em>array<br>     */<br>    </em><strong>protected </strong>$policies = [<br>        Task::<strong>class </strong>=&gt; TaskPolicy::<strong>class</strong>,<br>    ];</pre><pre>    <em>/**<br>     * Register any authentication / authorization services.<br>     *<br>     * </em><strong><em>@return </em></strong><em>void<br>     */<br>    </em><strong>public function </strong>boot()<br>    {<br>        $this-&gt;registerPolicies();<br>    }<br>}</pre><h4>Task List View</h4><p>To create a task list view, rename resources/views/home.blade.php to resources/views/tasks.blade.php then open up the renamed file and edit the contents.</p><pre><strong>@extends(</strong>&#39;layouts.app&#39;<strong>)<br><br>@section(</strong>&#39;content&#39;<strong>)<br></strong>&lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;row justify-content-center&quot;&gt;<br>        &lt;div class=&quot;col-md-8&quot;&gt;<br>            <strong>@if (</strong>session(&#39;status&#39;)<strong>)<br>                </strong>&lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>                    {{ session(&#39;status&#39;) }}<br>                &lt;/div&gt;<br>            <strong>@endif<br><br>            </strong>&lt;div class=&quot;card card-new-task&quot;&gt;<br>                &lt;div class=&quot;card-header&quot;&gt;New Task&lt;/div&gt;<br><br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    &lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;tasks.store&#39;) }}&quot;&gt;<br>                        <strong>@csrf<br>                        </strong>&lt;div class=&quot;form-group&quot;&gt;<br>                            &lt;label for=&quot;title&quot;&gt;Title&lt;/label&gt;<br>                            &lt;input id=&quot;title&quot; name=&quot;title&quot; type=&quot;text&quot; maxlength=&quot;255&quot; class=&quot;form-control{{ $errors-&gt;has(&#39;title&#39;) ? &#39; is-invalid&#39; : &#39;&#39; }}&quot; autocomplete=&quot;off&quot; /&gt;<br>                            <strong>@if (</strong>$errors-&gt;has(&#39;title&#39;)<strong>)<br>                                </strong>&lt;span class=&quot;invalid-feedback&quot; role=&quot;alert&quot;&gt;<br>                                    &lt;strong&gt;{{ $errors-&gt;first(&#39;title&#39;) }}&lt;/strong&gt;<br>                                &lt;/span&gt;<br>                            <strong>@endif<br>                        </strong>&lt;/div&gt;<br>                        &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Create&lt;/button&gt;<br>                    &lt;/form&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;card&quot;&gt;<br>                &lt;div class=&quot;card-header&quot;&gt;Tasks&lt;/div&gt;<br><br>                &lt;div class=&quot;card-body&quot;&gt;<br>                   &lt;table class=&quot;table table-striped&quot;&gt;<br>                       <strong>@foreach (</strong>$tasks <strong>as </strong>$task<strong>)<br>                           </strong>&lt;tr&gt;<br>                               &lt;td&gt;<br>                                   <strong>@if (</strong>$task-&gt;is_complete<strong>)<br>                                       </strong>&lt;s&gt;{{ $task-&gt;title }}&lt;/s&gt;<br>                                   <strong>@else<br>                                       </strong>{{ $task-&gt;title }}<br>                                   <strong>@endif<br>                               </strong>&lt;/td&gt;<br>                               &lt;td class=&quot;text-right&quot;&gt;<br>                                   <strong>@if (</strong>! $task-&gt;is_complete<strong>)<br>                                       </strong>&lt;form method=&quot;POST&quot; action=&quot;{{ route(&#39;tasks.update&#39;, $task-&gt;id) }}&quot;&gt;<br>                                           <strong>@csrf<br>                                           @method(</strong>&#39;PATCH&#39;<strong>)<br>                                           </strong>&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Complete&lt;/button&gt;<br>                                       &lt;/form&gt;<br>                                   <strong>@endif<br>                               </strong>&lt;/td&gt;<br>                           &lt;/tr&gt;<br>                       <strong>@endforeach<br>                   </strong>&lt;/table&gt;<br><br>                    {{ $tasks-&gt;links() }}<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><strong>@endsection</strong></pre><p>At the top, <strong>@extends(&#39;</strong>layouts.app&#39;<strong>) </strong>tells the blade templating engine we’re extending the layout at resources/views/layouts/app.blade.php. Next we’re using the @section directive with the argument &#39;content&#39; to define the content of our template which will be rendered in the content section of our app layout.</p><p>Any messages flashed to the session under the key of status will be shown to the user because of the conditional statement @if (session(&#39;status&#39;). Inside this statement is a div with <a href="https://v4-alpha.getbootstrap.com/components/alerts/">Bootstrap classes</a> for an alert which displays the contents of session(&#39;status&#39;).</p><p>In the &lt;div class=&quot;card card-new-task&quot;&gt; tag we are defining a form for the user to use to create new tasks. The form’s action {{ route(&#39;tasks.store&#39;) }} uses Laravel’s <a href="https://laravel.com/docs/5.7/helpers#method-route">route helper method</a> to generate a URL for our form to POST to. The @csrf blade directive generates a Cross-Site Request Forgery token. The conditional blade directive <strong>@if (</strong>$errors-&gt;has(&#39;title&#39;)<strong>)</strong> checks if the <a href="https://laravel.com/docs/5.6/validation#working-with-error-messages">errors message bag</a> has an entry for title. If it does it will render the HTML inside the directive, in our case showing the error message with {{ $errors-&gt;first(&#39;title&#39;) }}.</p><p>Next in the &lt;div class=&quot;card&quot;&gt; tag we have our table of tasks. We loop through each task in the $tasks paginator with the <a href="https://laravel.com/docs/5.7/blade#loops">blade directive</a> <strong>@foreach (</strong>$tasks <strong>as </strong>$task<strong>) </strong>and write a table row for each one. In the first &lt;td&gt; tag we conditionally show the task name with or without the &lt;s&gt; <a href="https://www.w3schools.com/tags/tag_s.asp">tag</a> in order to toggle strikethrough depending on if the task has been completed. In the second &lt;td&gt; tag we’re conditionally showing a form only when the task is incomplete. This form again uses the route() helper method to generate a URL for our form to POST to only this time we’re specifying $task-&gt;id as a second argument so the helper method fills the route definition’s $task parameter with the task’s ID. In addition to the @csrf directive we used before, we’re using the @method directive to <a href="https://laravel.com/docs/5.7/routing#form-method-spoofing">spoof the form method</a> to be a PATCH instead of a POST.</p><p>Finally, the {{ $tasks-&gt;links() }} statement <a href="https://laravel.com/docs/5.7/pagination#displaying-pagination-results">generates pagination links</a> for display to our user.</p><p>There’s one CSS class we used in our view, .card-new-task that hasn’t been defined yet. Let’s do that now by editing resources/views/layouts/app.blade.php and adding a &lt;style&gt; tag to the bottom of the &lt;head&gt; tag.</p><pre>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;<br><br>    &lt;!-- CSRF Token --&gt;<br>    &lt;meta name=&quot;csrf-token&quot; content=&quot;{{ csrf_token() }}&quot;&gt;<br><br>    &lt;title&gt;{{ config(&#39;app.name&#39;, &#39;Laravel&#39;) }}&lt;/title&gt;<br><br>    &lt;!-- Scripts --&gt;<br>    &lt;script src=&quot;{{ asset(&#39;js/app.js&#39;) }}&quot; defer&gt;&lt;/script&gt;<br><br>    &lt;!-- Fonts --&gt;<br>    &lt;link rel=&quot;dns-prefetch&quot; href=&quot;https://fonts.gstatic.com&quot;&gt;<br>    &lt;link href=&quot;https://fonts.googleapis.com/css?family=Nunito&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;<br><br>    &lt;!-- Styles --&gt;<br>    &lt;link href=&quot;{{ asset(&#39;css/app.css&#39;) }}&quot; rel=&quot;stylesheet&quot;&gt;<br>    &lt;style&gt;<br>        .card-new-task {<br>            margin-bottom: 20px;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;</pre><h3>Using Our Application</h3><p>Refresh the task-app.test page in your browser to see the results of our work. When a user logs in, they are redirected to /tasks. If a user is already logged in and on the welcome page, the upper right corner now contains a link to the Tasks page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*sK29Bc2pKlbZlNwKJVoH_A.png" /></figure><p>Navigate to the Tasks page.</p><p>There’s now a New Task card at the top of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*f9jFkc9Rys6gUInjw30qQw.png" /></figure><p>Followed by a Tasks card with a paginated table of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*BusMnZoSfZe7kxkus8j-Ag.png" /></figure><p>Incomplete tasks are listed first. Later in the pagination are completed tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*98p3e0viMAMhziz-g9lCVg.png" /></figure><p>Let’s test our application by creating a new task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*egYlaXolFj8sA5DGEnKUvA.png" /></figure><p>You’ll see the confirmation message we’re flashing to the session after clicking “Create”. Our new task appears at the top of our task list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*DLJ_lZUElroWgmoGksOdhA.png" /></figure><p>Click “Complete” next to our newly created task. The task will be marked as complete and be shown at the beginning of the completed tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*Ld5737P9erKMMf3OryggJg.png" /></figure><p>Go ahead and log out of the application using the menu in the upper right corner. Log in as the other user you registered and see there is an entirely different list. Each user has their own private list of tasks!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*WmM-j08T_Zb7Hs1nS3_VDg.png" /></figure><p>As you create new tasks, they will appear in your task list.</p><h3>Conclusion</h3><p>That’s it! With very little effort, thanks to the Laravel framework, we’ve implemented a user-based task list application complete with user accounts, private task lists, and password resets.</p><p>We learned about <a href="https://laravel.com/docs/5.7/authentication">authentication</a>, route <a href="https://laravel.com/docs/5.7/routing#route-groups">middleware and groups</a>, <a href="https://laravel.com/docs/5.7/controllers#resource-controllers">resource routes</a>, <a href="https://laravel.com/docs/5.7/artisan">artisan commands</a>, <a href="https://laravel.com/docs/5.7/migrations">database migrations</a>, eloquent <a href="https://laravel.com/docs/5.7/eloquent">models</a>, <a href="https://laravel.com/docs/5.7/eloquent-relationships">relationships</a>, <a href="https://laravel.com/docs/5.7/eloquent-mutators">mutators</a>, <a href="https://laravel.com/docs/5.7/authorization#writing-policies">policies</a>, <a href="https://laravel.com/docs/5.7/seeding">factories and seeders</a>, <a href="https://laravel.com/docs/5.7/blade">blade directives</a>, <a href="https://laravel.com/docs/5.7/pagination">pagination</a>, and <a href="https://laravel.com/docs/5.7/session#flash-data">flashing to the session</a>.</p><p>You can view the source code for this project <a href="https://github.com/bricehartmann/laravel-5.7-task-app">on GitHub</a>.</p><p>Thanks for reading! See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eff4a07e2688" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>