<?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 Asia Joumaa on Medium]]></title>
        <description><![CDATA[Stories by Asia Joumaa on Medium]]></description>
        <link>https://medium.com/@asia.joumaa?source=rss-50372b929418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PAzBLJnPCXJdnz_0EdgIZg.jpeg</url>
            <title>Stories by Asia Joumaa on Medium</title>
            <link>https://medium.com/@asia.joumaa?source=rss-50372b929418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:37:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asia.joumaa/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[Deploy a Laravel App into a Docker Container]]></title>
            <link>https://medium.com/@asia.joumaa/deploy-a-laravel-app-into-a-docker-container-af96ac58411d?source=rss-50372b929418------2</link>
            <guid isPermaLink="false">https://medium.com/p/af96ac58411d</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[docker-run]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Asia Joumaa]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 06:50:50 GMT</pubDate>
            <atom:updated>2022-12-10T06:50:50.911Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever you search on google you find tutorials on how to deploy Laravel App with docker-compose not just docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*M-HoF7qx8AlSu9lzO4JmUA.png" /></figure><h3>But what is the difference between Docker and Docker Compose?</h3><ol><li><strong>Docker run</strong> is entirely command line based, while <strong>docker-compose</strong> reads configuration data from a YAML file.</li><li><strong>Docker run</strong> can only start one container at a time, while <strong>docker-compose</strong> will configure and run multiple containers.</li></ol><p>When you are working with <strong>Laravel</strong>, you need <strong>multiple services</strong> to be configured while starting Laravel project, like: MySQL database, redis, mailhog and other services. All these can be configured together using docker-compose and they <strong>become connected</strong> to each other. But sometimes we just need to <strong>configure one container</strong> for our laravel project without reconfiguring all other services.</p><blockquote>Here this tutorial come in handy, I will explain step by step how to install Laravel App project into a Docker container.</blockquote><h3>Prerequisite:</h3><p>Laravel project downloaded on your local environment.</p><h3>Creating and writing into Dockerfile:</h3><h4>Step 1: Create a Dockerfile:</h4><p>Let’s start of by adding a docker file to the laravel project. So, in the root of the project add a new file called Dockerfile.</p><h4>Step 2: Choose the right base image</h4><p>After adding this Dockerfile, we need to write the first instruction which is FROM. FROM instruction is used to specify the base image. In our case the image will be operating system (alpine preferable) plus a run time environment which is PHP version that our project needs. Inorder to know which image to use we need to</p><ol><li>Navigate to <a href="https://hub.docker.com/">https://hub.docker.com/</a>.</li><li>Write PHP in the search field on the top.</li><li>Click on PHP (Docker Official Image) — you will be navigated to php page</li><li>Click on tags</li><li>Write php version of the project in <em>Filter Tags</em> search input.</li><li>Copy the tag of this image</li><li>Paste the tag in the Dockerfile as follow:</li></ol><pre>FROM php:8.0.24-zts-alpine3.16</pre><h4>Step 3: Changing the working directory</h4><p>For php projects we need to move all our files to /var/www/html folder. So let us add below FROM instruction:</p><pre>WORKDIR /var/www/html</pre><h4>Step 4: Excluding files and directories</h4><p>Before copying Laravel app directories and files we need to exclude couple of folders that are not needed to be transferred to the image. We will add another file in the directory and name it: <strong>.dockerignore</strong> Inside it we will add the following:</p><pre>vendor/</pre><p>Hence, when building an image, docker will not copy this large directory to docker engine. Therefore, it will reduce build context massively.</p><h4>Step 5: Installing all prerequisite packages</h4><p>Before executing composer install, we have to install all the packages needed in our project. I will list here the common prerequests for all laravel projects, and you can add to them as much as needed.</p><pre>RUN apk update <br>RUN curl -sS https://getcomposer.org/installer | php -- --version=1.10.26 --install-dir=/usr/local/bin --filename=composer</pre><h4>Step 6: Copying files and directories</h4><p>Now that we have a base image, and we are in the correct directory, next step is to copy the application files into the image. To do so, we simply need to add copy instruction as follow:</p><pre>COPY . .</pre><h4>Step 7: Running commands</h4><p>Next step we are going to install project dependencies using composer. We will use the <strong>RUN</strong> command. Add this line:</p><pre>RUN composer install</pre><h4>Step 8: Defining entrypoints</h4><p>Whenever we want to start a laravel application we have to execute this command: <strong>php artisan serve — host=0.0.0.0</strong> Same in docker, to start the project we need this command in execute form to start our project, so we will add this line in the last line of Dockerfile</p><pre>CMD [&quot;php&quot;,&quot;artisan&quot;,&quot;serve&quot;,&quot;--host=0.0.0.0&quot;]</pre><h4>Our final Dockerfile is as follow</h4><pre>FROM php:8.0.24-zts-alpine3.16<br>WORKDIR /var/www/html<br><br>RUN apk update <br>RUN curl -sS https://getcomposer.org/installer | php -- --version=2.4.3 --install-dir=/usr/local/bin --filename=composer<br><br>COPY . .<br>RUN composer install<br><br>CMD [&quot;php&quot;,&quot;artisan&quot;,&quot;serve&quot;,&quot;--host=0.0.0.0&quot;]</pre><h3>Build and run your container</h3><h4>Build</h4><p>Whenever we want to start this Laravel project, you need to navigate to project files and build it using this command:</p><pre>docker build -t laravel-app .</pre><h4>Run</h4><p>When done build, you will have to run the project using the following command:</p><pre>docker run -d -p 81:8000 --name backend laravel-app</pre><h4>Open browser</h4><p>Now in your browser write: localhost:81</p><h3>Conclusion</h3><p>With only couple of commands you can deploy your Laravel project on docker, and leave all other services your project attached to as is.</p><p>Happy Coding ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af96ac58411d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL Join vs In vs Exists Which One is Faster]]></title>
            <link>https://medium.com/@asia.joumaa/mysql-join-vs-in-vs-exists-which-one-is-faster-e3abb6ce6192?source=rss-50372b929418------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3abb6ce6192</guid>
            <category><![CDATA[distinct]]></category>
            <category><![CDATA[join]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[innerjoin]]></category>
            <dc:creator><![CDATA[Asia Joumaa]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 06:41:37 GMT</pubDate>
            <atom:updated>2022-10-06T07:10:58.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*JMnxtdiELTdkk4WtOJGq5Q.jpeg" /></figure><p>I faced an issue last week, I had a page that took time more than expected to be viewed. After looking into it, I got that<strong> one query is causing this delay</strong>.</p><p>Let me discuss more what happened:</p><p>I had two tables one called surveys and other is tasks. I had <strong>huge number of tasks, each task is attached to one of the surveys</strong>. Apparently, I don’t have this huge number of surveys, it is just 5. So huge number of tasks are just attached to 5 different surveys.</p><h3>The ER Diagram is as follow:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XP2po_Jm3ao088sowS4qkg.png" /></figure><p>The query should only <strong>list the surveys attached to the tasks</strong>. Let us discuss the solutions I tried.</p><h3>MySQL Exists Code:</h3><p>Laravel default solution is to use where exists query, it is as follow:</p><pre>select<br>  *<br>from<br>  `surveys`<br>where<br>  <strong>exists</strong> (<br>    select<br>      *<br>    from<br>      `tasks`<br>    where<br>      `surveys`.`id` = `tasks`.`survey_id`<br>      and `tasks`.`survey_id` is not null<br>      and `tasks`.`deleted_at` is null<br>  )<br>  and `surveys`.`deleted_at` is null<br>limit<br>  25 offset 0</pre><p>This query took <strong>2,322.40ms</strong> 😮.</p><p>Even though from the documentation:</p><blockquote>Where exists stops for further execution as soon as it finds the first true occurrence.</blockquote><h3>MySQL Join Code:</h3><p>I decided then to try join instead of where exists, from some resources online, join takes less time in executing.</p><p>The new query is as follow:</p><pre>select<br>  `surveys`.`id`,<br>  `tasks`.`survey_id`<br>from<br>  `surveys`<br>  <strong>inner join</strong> `tasks` on `surveys`.`id` = `tasks`.`survey_id`<br>where<br>  `tasks`.`survey_id` is not null<br>  and `surveys`.`deleted_at` is null<br>group by<br>  `tasks`.`survey_id`<br>limit<br>  25 offset 0</pre><p>This query in the exact number of data took <strong>17,537.12ms</strong> 😖. This is even worst.</p><p>This took more time because:</p><blockquote>Exists statement works faster than that of Joins. Exists will give you a single record and will save the time also. In case of joins the number of records will be more and all the records must be used.</blockquote><p>So, you should <strong><em>only use join, when you need the whole data from both tables.</em></strong></p><h3>Distinct and In:</h3><p>My final solution is to get the distinct ids from tasks table, and then just get list of surveys details that are in the second table.</p><p>The query is as follow:</p><pre>select<br>  <strong>Distinct</strong> survey_id<br>from<br>  `tasks`<br>where<br>  and `tasks`.`survey_id` is not null<br>  and `tasks`.`deleted_at` is null</pre><p>Then you will get all surveys that are IN list of ids we got from the above query.</p><p>Thankfully this took <strong>1,829.77ms</strong>, still took much time, but it is the best solution from the above two.</p><h3>Pagination:</h3><p>But, we need this output paginated. To perform pagination in the frontend, <strong>I need total number</strong> of surveys attached to the tasks, and then just get the first 25.</p><p>When using <strong>Where Exists</strong>, I will have to call same query two times, one with select count(id) and the second as the first query. in total these two queries will take 4<strong>,521.30ms!!</strong> 😮 <strong>execution time is doubled.</strong></p><p>While using <strong>Join</strong>, also I had to fetch same query twice, the first one to get total number of surveys, and the second one to fetch the data. in total <strong>35,074.9ms 😢.</strong></p><p>When using <strong>Distinct and In</strong>, I had to execute select distinct surveys, then count them, then execute <em>select from surveys in just 25 ids</em> to fetch the needed data. In total will get the same execution time which is <strong>1,829.77ms 😍.</strong></p><blockquote>So choosing Distinct and in queries had cut the execution number into half!!</blockquote><p>To Wrap it up, whenever you have a huge number of data from a table, and you need to seek out data from another table that is related to the first, use <strong>Distinct and in</strong> <strong>code</strong> it is the most optimised solution in this case.</p><p>Happy coding everyone ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3abb6ce6192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing props through a function from Child React Component]]></title>
            <link>https://medium.com/@asia.joumaa/passing-props-from-child-react-component-3ed05a82ac15?source=rss-50372b929418------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed05a82ac15</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[props]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Asia Joumaa]]></dc:creator>
            <pubDate>Sun, 07 Aug 2022 09:47:08 GMT</pubDate>
            <atom:updated>2022-08-07T09:48:22.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*96lj0j5zGznrqNIUUpU3iQ.png" /><figcaption>Calling print function</figcaption></figure><p>I wanted to share with you a small explanation on how to read props through a function from child reactJs component.</p><p><em>Simple yet important to know how to use it.</em></p><h3>Define a add function</h3><p>As we all know, a function has two attributes it’s props and the return type. So in C++ language we actually define a function like this:</p><pre><strong>int</strong> function add (<strong>int a, int b</strong>) {}</pre><p>This means that this function will take two props — a and b — and returns an int.</p><p>In JavaScript we don’t add the type of returned value so we define a function like this:</p><pre>function add(<strong>a, b</strong>) {}</pre><p>in TypeScript we actually add the type of each prop like this, and may add the type of return attribute as well:</p><pre>function add(<strong>a:number, b:number</strong>): <strong>number</strong> {}</pre><p>And using arrow function we write it this way</p><pre>let add <strong>=</strong> (a:number, b:number) <strong>=&gt;</strong> {}</pre><p>Ok! enough with the ways of defining a function, let us move to using this function in React components.</p><h3>Call functions in ReactJs component</h3><p>Mainly to use any function we need just to call it’s name and fill it’s props, like this</p><pre>const Component = () =&gt; {<br>   let [number, setNumber] = useState(0);</pre><pre>   let add = (a, b) =&gt; {<br>      setNumber(a+b);<br>   }</pre><pre>   return (&lt;&gt;<br>            &lt;Button onClick={<strong>()=&gt;add(6,2)</strong>}&gt;Add&lt;/Button&gt;<br>            &lt;p&gt;{number}&lt;/p&gt;<br>          &lt;&gt;);</pre><pre>}</pre><p>In this example initially we will have a button and 0. Upon clicking on the button it will show 8 instead of 0.</p><h3>Passing a function to the child ReactJs component</h3><p>Let us now get these props (a, b) from a child component.</p><pre>const Component = () =&gt; {<br>   let [number, setNumber] = useState(0);</pre><pre>   let add = (a, b) =&gt; {<br>      setNumber(a+b);<br>   }</pre><pre>return (&lt;&gt;<br>            &lt;ChildComponent <strong>addFunction={(x,y)=&gt;add(x,y)}</strong> /&gt;<br>            &lt;p&gt;{number}&lt;/p&gt;<br>          &lt;&gt;);</pre><pre>}</pre><pre>const ChildComponent = (props) =&gt; (<br>    &lt;Button onClick={<strong>props.addFunction(6,2)</strong>}&gt;Add&lt;/Button&gt;</pre><pre>);</pre><p>In this example we are taking a and b props from the child component. <strong>a is x</strong> and <strong>b is y</strong>.</p><p>What if we want a third number to be added but from parent component. We can do like this:</p><pre>const Component = () =&gt; {<br>   let [number, setNumber] = useState(0);</pre><pre>   let add = (a, b, c) =&gt; {<br>      setNumber(a+b+c);<br>   }</pre><pre>   return (&lt;&gt;<br>            &lt;ChildComponent <strong>addFunction={(x,y)=&gt;add(x,y,8)}</strong> /&gt;<br>            &lt;p&gt;{number}&lt;/p&gt;<br>          &lt;&gt;);</pre><pre>}</pre><pre>const ChildComponent = (props) =&gt; (<br>    &lt;Button onClick={<strong>props.addFunction(6,2)</strong>}&gt;Add&lt;/Button&gt;</pre><pre>);</pre><p>In this example, we are still taking x and y from the child component, but we have added another number from the parent component.</p><blockquote>In the first parenthesis (x,y) are the variables we are getting from the child component, and after the add function we added the props we are sending to function.</blockquote><p>Let us put another example with the same idea above</p><pre>const Component = () =&gt; {<br>   let [number, setNumber] = useState(0);</pre><pre>   let add = (a, b, c) =&gt; {<br>      setNumber(a+b+c);<br>   }</pre><pre>   return (&lt;&gt;<br>            &lt;ChildComponent <strong>addFunction={(x,y)=&gt;add(x,4,8)</strong>} /&gt;<br>            &lt;p&gt;{number}&lt;/p&gt;<br>          &lt;&gt;);</pre><pre>}</pre><pre>const ChildComponent = (props) =&gt; (<br>    &lt;Button onClick={<strong>()=&gt;props.addFunction(6,2)</strong>}&gt;Add&lt;/Button&gt;</pre><pre>);</pre><p>The difference in this example is that we are getting x and y numbers from child component, but we are just sending the x as a prop to the add function.</p><p>So, this is how we pass props to a function from parent and child components.</p><p>Oh wait, I have a little thing to be added down here.</p><p>Sometimes we see this:</p><pre>&lt;AnotherComponent addFunction={<strong>add</strong>} /&gt;</pre><p>We are calling a function without precising what attributes to be taken from child component and which ones to be sent to the add function.</p><p>This term is equivalent to this:</p><pre>&lt;AnotherComponent addFunction={<strong>(x,y)=&gt;add(x,y)</strong>} /&gt;</pre><p>By default we are sending to the function all the attributes we are getting from the child component.</p><p>That’s it!</p><p>Happy coding everyone ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed05a82ac15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphic Relationship in Laravel]]></title>
            <link>https://medium.com/@asia.joumaa/polymorphic-relationship-in-laravel-2384bc63e9ef?source=rss-50372b929418------2</link>
            <guid isPermaLink="false">https://medium.com/p/2384bc63e9ef</guid>
            <category><![CDATA[morph]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[polymorphic-relations]]></category>
            <dc:creator><![CDATA[Asia Joumaa]]></dc:creator>
            <pubDate>Sun, 31 Oct 2021 08:34:28 GMT</pubDate>
            <atom:updated>2021-10-31T08:34:28.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvUb33oPpKllPBOKxVRW4A.jpeg" /></figure><p>Let’s start our blog with this small exercise. I want to create a Laravel blog webpage having this scenario: <strong>a user can input multi images when writing a post, and when commenting on a specific post.</strong></p><p>Directly a developer will create 4 tables:</p><pre><strong>posts:<br></strong>id<br>title<br>text</pre><pre><strong>post_images:<br></strong>id<br>url<br>image_type<br>post_id</pre><pre><strong>comments:<br></strong>id<br>text<br>post_id</pre><pre><strong>comment_images:<br></strong>id<br>url<br>image_type<br>comment_id</pre><p>Models of each will be as below</p><pre>class <strong>Post</strong> extends Model {</pre><pre>  public function images {<br>    return $this-&gt;hasMany(PostImage::class);<br>  }</pre><pre>  public function comments {<br>    return $this-&gt;hasMany(Comment::class);<br>  }<br>}<br></pre><pre>class <strong>PostImage</strong> extends Model {</pre><pre>  public function post {<br>    return $this-&gt;belongsTo(Post::class);<br>  }<br>}<br></pre><pre>class <strong>Comment</strong> extends Model {</pre><pre>  public function images {<br>    return $this-&gt;hasMany(CommentImage::class);<br>  }</pre><pre>  public function post {<br>    return $this-&gt;belongsTo(Post::class);<br>  }<br>}<br></pre><pre>class <strong>CommentImage</strong> extends Model {</pre><pre>  public function comment {<br>    return $this-&gt;belongsTo(Comment::class);<br>  }<br>}</pre><p>What if we have a feature to <strong>view all images that belongs to specific post</strong></p><pre>$post_images = PostImage::select(&#39;id&#39;,&#39;url&#39;)-&gt;where(&#39;post_id&#39;,$post_id)-&gt;get();</pre><pre>$comment_images = CommentImage::select(&#39;id&#39;,&#39;url&#39;)-&gt;whereHas(&#39;post&#39;, function (Builder $query) use ($post_id) {<br>  $query-&gt;where(&#39;post_id&#39;,$post_id);<br>})-&gt;get();</pre><pre><strong>$images</strong> = $post_images-&gt;merge($comment_images);</pre><p>We are going to face some challenges to retrieve images belongs to post paginated.</p><h4>Ok so let’s enhance this by using Polymorphic Relationship</h4><h3>Polymorphic Relationship</h3><p>Polymorphic relationship allows you to have</p><blockquote><strong>one table</strong> <strong>related to two or more different tables</strong>.</blockquote><h4>HOW!!</h4><p>Instead of 4 tables (posts, post_images, comments and comment_images) we are going to create 3 tables:</p><pre><strong>posts:<br></strong>id<br>title<br>text</pre><pre><strong>comments:<br></strong>id<br>text<br>post_id</pre><pre><strong>images:<br></strong>id<br>url<br>image_type<br><strong>parentable_id<br>parentable_type</strong></pre><h4>Oh wait! what are <strong>parentable_id</strong> and <strong>parentable_type</strong> fields mean??!</h4><p>When you join comment_images and post_images in one table, we will need to replace comment_id/post_id with one common attribute i named it <strong>parent</strong>. This parent is related to a full model, it might be comment or post, to distinguish between these two tables (comments/posts) we have to separate parent field into two fields (id and type), id is the foreign id, and type directs us to which table this data is related.</p><blockquote>Laravel adds “able” to all morph attributes to distinguish it from other attributes.</blockquote><p>so eventually we’ll be having like this example (id=213, url=image.png, image_type=png, parentable_id=3, parentable_type=comment).</p><p>Ok great!!</p><h4>But! how to implement this morph relationship in Laravel?</h4><p>First let’s create images table using migration having this morph relationship</p><pre><strong>&lt;?php</strong><br><br>use Illuminate\Database\Migrations\Migration;<br>use Illuminate\Database\Schema\Blueprint;<br>use Illuminate\Support\Facades\Schema;<br><br>class ImagesTable extends Migration<br>{<br>    /**<br>     * Run the migrations.<br>     *<br>     * @return void<br>     */<br>    public function up()<br>    {<br>        Schema::create(&#39;images&#39;, function (Blueprint $table) {<br>            $table-&gt;id();<br>            $table-&gt;string(&#39;url&#39;);<br>            $table-&gt;string(&#39;image_type&#39;);<br>            <strong>$table-&gt;morphs(&#39;parentable&#39;);</strong><br>            $table-&gt;timestamps();<br>        });<br>    }<br><br>    /**<br>     * Reverse the migrations.<br>     *<br>     * @return void<br>     */<br>    public function down()<br>    {<br>        Schema::drop(&#39;images&#39;);<br>    }<br>}</pre><p><strong>Models will be as follow</strong></p><pre>class <strong>Image</strong> extends Model {</pre><pre>  <strong>public function parentable {<br>    return $this-&gt;morphTo();<br>  }</strong><br>}<br></pre><pre>class <strong>Post</strong> extends Model {</pre><pre>  public function images {<br>    return $this-&gt;morphMany(Image::class, &#39;parentable&#39;);<br>  }</pre><pre>  public function comments {<br>    return $this-&gt;hasMany(Comment::class);<br>  }<br>}<br></pre><pre>class <strong>Comment</strong> extends Model {</pre><pre>  public function images {<br>    return $this-&gt;morphMany(Image::class, &#39;parentable&#39;);<br>  }</pre><pre>  public function post {<br>    return $this-&gt;belongsTo(Post::class);<br>  }<br>}</pre><p>If we want to <strong>retrieve all images in specific post</strong></p><pre>$images = Images::<strong>whereHasMorph</strong>(<br>    &#39;parentable&#39;, <br>    [&#39;App\Post&#39;, &#39;App\Comment&#39;], // or you can use * for all<br>    function (Builder $query, $type) {<br>        if ($type === &#39;App\Post&#39;) use ($post_id) {<br>            $query-&gt;where(&#39;id&#39;, $post_id);<br>        }</pre><pre>        if ($type === &#39;App\Comment&#39;) use ($post_id) {<br>            $query-&gt;where(&#39;post_id&#39;, $post_id);<br>        }<br>    }<br>)-&gt;get(); // we can do pagination</pre><p>If we want to <strong>get</strong> <strong>each image’s parent data</strong>, of course with <a href="https://medium.com/@asia.joumaa/lazy-loading-in-laravel-5cc0098510ce">lazy loading</a>.</p><blockquote>You can check <a href="https://medium.com/@asia.joumaa/lazy-loading-in-laravel-5cc0098510ce">my previous blog about lazy loading</a>.</blockquote><pre>$images = Images::with(&#39;parentable&#39;)-&gt;get();</pre><pre>foreach ($images as $image) {<br>     var_dump($image-&gt;parentable); // <strong>you will get comment or post object.</strong><br>}</pre><p>below is the way to <strong>set image with morph relationship</strong></p><pre>$post = Post::find(1);<br></pre><pre><strong>//usual case<br></strong>$new_image = Image::create([<br>   &#39;url&#39; =&gt; &#39;new_image_url.jpg&#39;,<br>   &#39;image_type&#39; =&gt; &#39;image/jpg&#39;,<br>   &#39;parentable_id&#39; =&gt; $post-&gt;id,<br>   &#39;parentable_type&#39; =&gt; Post::class<br>]);<br></pre><pre><strong>//or you can use associate function like below<br></strong>$new_image = Image::create([<br>   &#39;url&#39; =&gt; &#39;new_image_url.jpg&#39;,<br>   &#39;image_type&#39; =&gt; &#39;image/jpg&#39;<br>]);<br>$new_image-&gt;parentable()-&gt;associate($post);<br>$new_image-&gt;save();</pre><p>Morph is a special relationship created in Laravel to enhance the structure of the database tables. Use it when it’s convenient like the example above.</p><p>If you have any question, don’t hesitate in commenting below.</p><p>Happy coding everyone!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2384bc63e9ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading in Laravel]]></title>
            <link>https://medium.com/@asia.joumaa/lazy-loading-in-laravel-5cc0098510ce?source=rss-50372b929418------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cc0098510ce</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[enhancement]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <dc:creator><![CDATA[Asia Joumaa]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 14:01:52 GMT</pubDate>
            <atom:updated>2021-10-11T10:10:04.477Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>From 1000 to 4 Queries per Request</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X6aqwsv3vZPq9WZKq4okw.jpeg" /></figure><p>In order to enhance your Laravel project performance, you definitely have to know about lazy loading, why it is used and how to implement it. When you implement lazy loading you will decrease number of connections on the database from 1000 queries per request into 3 or 4 queries per request!!</p><blockquote>Goal: Increase the performance by decreasing number of connections sent to the database.</blockquote><p>You want to know how!? <strong>Continue reading</strong></p><p>To implement lazy loading you need keep in mind these two important functions when fetching data, <strong>with</strong> and <strong>withCount.</strong></p><h3>What is With function and how to use it?</h3><p>Let’s have this example: We are building platform that shows list of students and in which school he is enrolled in beside each. So we have two main tables in the database <strong>Student</strong> and <strong>School</strong>.</p><p><strong>Student</strong> table will have <strong>id</strong> and <strong>name</strong> columns, and <strong>School</strong> will have <strong>id</strong> and <strong>name</strong> columns.</p><p>A student is enrolled in one school, and a school might have one or more students enrolled this year. To achieve this relation we will add <strong>school_id</strong> attribute to students table.</p><p>The models of each student and school will be as below:</p><pre>class Student extends Model {</pre><pre>  public function school {<br>    return $this-&gt;belongsTo(School::class)</pre><pre>  }<br>}</pre><pre>class School extends Model {</pre><pre>  public function students {<br>    return $this-&gt;hasMany(Student::class)</pre><pre>  }<br>}</pre><p>Now in the view we will have to fetch student’s names and school respectively. The code is as follow</p><pre>// Fetch students <br>$students = Student::all();</pre><pre>// Echo school name for each student<br>foreach ($students as $student) {</pre><pre>  echo $student-&gt;school-&gt;name;<br>}</pre><p>The code will be working perfectly this way. But let’s dig deep into database requests for this example.</p><pre>$students = Student::all(); // <strong>select * from students;</strong></pre><pre>foreach ($students as $student) {</pre><pre>  echo $student-&gt;school-&gt;name; //<strong> select * from schools where id = x;</strong><br>}</pre><p>Number of database connection in this example is<em> 1+n</em>. Whenever we are asking for school name we are requesting new query, because</p><blockquote><strong>the relationship data is not loaded until we have first access to the property</strong>.</blockquote><p><em>Let’s solve this issue!</em></p><p>Amazingly Laravel has <strong>with</strong> function, this small function can retrieve all the data needed and save them in memory. The code will become as follow:</p><pre>$students = Student::with(&#39;school&#39;)-&gt;all();<br>// <strong>select * from students;<br></strong>// <strong>select * from schools where id in (x,y,z....);</strong></pre><pre>foreach ($students as $student) {</pre><pre>  echo $student-&gt;school-&gt;name;<br>}</pre><p>Number of database connections = 2.</p><blockquote>It’s always preferable to choose specific columns we need to be fetched instead of *.</blockquote><p>So here you go</p><pre>$students = Student::select(&#39;id&#39;,&#39;school_id&#39;)-&gt;with(&#39;school:id,name&#39;)-&gt;get(); <br>// <strong>select id, school_id from students;<br></strong>// <strong>select id, name from schools where id in (x,y,z....);</strong></pre><pre>foreach ($students as $student) {</pre><pre>  echo $student-&gt;school-&gt;name;<br>}</pre><h3>What is WithCount function and how to use it?</h3><p>Now we will have to show list of schools, and beside each count of students enrolled. Below is a working code</p><pre>$schools = School::all();</pre><pre>foreach ($schools as $school) {</pre><pre>  echo $school-&gt;students()-&gt;count(); <br>}</pre><p>Now let’s check database requests while compiling such code</p><pre>$schools = School::all(); // <strong>select * from schools;</strong></pre><pre>foreach ($schools as $school) {</pre><pre>  echo $school-&gt;students()-&gt;count(); // <strong>select count(*) from students where school_id = x group by school_id;</strong><br>}</pre><p>This too has n+1 problem. To solve this we will be using <strong>withCount.</strong></p><pre>$schools = School::withCount(&#39;students&#39;)-&gt;get(); <br>// <strong>select * from schools;<br>// select count(*) as students_count from students where school_id in (x,y,z...) group by school_id;</strong></pre><pre>foreach ($schools as $school) {</pre><pre>  echo $school-&gt;students_count; <br>}</pre><p>Number of database connections = 2.</p><blockquote>WithCount function will add directly {relationship}_count attribute to the model to use it freely.</blockquote><p>Lazy loading surely decrease number of connections to the database, but make sure you don’t over crowd your project’s memory.</p><p>If you have any question, don’t hesitate in commenting below.</p><p>Happy coding everyone!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cc0098510ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>