<?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 Rishni Meemeduma on Medium]]></title>
        <description><![CDATA[Stories by Rishni Meemeduma on Medium]]></description>
        <link>https://medium.com/@ashameemeduma?source=rss-eb5ef941055d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6UyU5qP9mci6wvqXHWL77Q.jpeg</url>
            <title>Stories by Rishni Meemeduma on Medium</title>
            <link>https://medium.com/@ashameemeduma?source=rss-eb5ef941055d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:25:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashameemeduma/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[Optimizing Subqueries in Laravel: An Efficient Approach Using addSelect]]></title>
            <link>https://medium.com/@ashameemeduma/optimizing-subqueries-in-laravel-an-efficient-approach-using-addselect-18338f013ac5?source=rss-eb5ef941055d------2</link>
            <guid isPermaLink="false">https://medium.com/p/18338f013ac5</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[addselect]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[eloquent]]></category>
            <dc:creator><![CDATA[Rishni Meemeduma]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 19:28:51 GMT</pubDate>
            <atom:updated>2025-03-31T19:40:22.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVeoYPMwTx5vBJQqhDmgNw.png" /></figure><p>With method involves leveraging Eloquent relationships to load related data. By using with(&#39;logins&#39;), you are preloading the logins relationship for each user. This approach is more suitable when you want to access all related records for a user (e.g., all login records). It provides an array or collection of related models, enabling you to work with and manipulate this data as needed.</p><pre>$users = User::query()<br>        -&gt;with(&#39;logins&#39;)<br>        -&gt;orderBy(&#39;name&#39;)<br>        -&gt;get();</pre><p><strong>Using Subqueries with </strong><strong>addSelect</strong></p><p>This method involves writing a subquery within the main query itself. I<strong><em>nstead of loading the entire relationship, it focuses on retrieving a specific piece of information for each user </em></strong>— in this case, the created_at value of the user&#39;s latest login record. By using addSelect with a subquery, you&#39;re efficiently embedding a calculated column (last_login_at) directly into the result set. The subquery:</p><pre>$users = Users::query()<br>        -&gt;addSelect([&#39;last_login_at&#39; =&gt; Logins::select(&#39;created_at&#39;)<br>          -&gt;whereColumn(&#39;user_id&#39;, &#39;users.id&#39;)<br>          -&gt;latest()<br>          -&gt;take(1)<br>         ])<br>          -&gt;orderBy(&#39;name&#39;)<br>          -&gt;paginate();</pre><p>This is the query that generated by above addSelect</p><pre>select users.*, <br>(<br>  select created_at <br>  from logins <br>  where user_id = users.id<br>  order by created_at desc<br>  limit 1 <br>) as last_login_at<br>from users<br>order by name asc<br>limit 15 offset 0<br></pre><ul><li><strong>Relationships and </strong>with: Ideal for loading entire related models and working with collections of related data.</li><li><strong>Subqueries with </strong>addSelect: Best suited for optimizing queries by retrieving specific calculated fields or summaries, avoiding the overhead of loading full related models.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18338f013ac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Bulk Insert Data to database using Laravel]]></title>
            <link>https://medium.com/@ashameemeduma/how-to-bulk-insert-data-to-database-using-laravel-d55aeaeaf4c5?source=rss-eb5ef941055d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55aeaeaf4c5</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[csv-to-mysql]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-bulk-insertions]]></category>
            <dc:creator><![CDATA[Rishni Meemeduma]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 22:11:44 GMT</pubDate>
            <atom:updated>2025-02-13T22:11:44.275Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wf_A5FsvQxN6XhArwn2nSQ.jpeg" /></figure><p>What if we had a csv file with millions of records to import to the database using Laravel. There are four approaches we can take.</p><ol><li>We can import one by one. This will work but It will exceed the maximum execution time. So, it’s might be memory efficient but not a computational efficient approach.</li></ol><pre>$path = storage_path(&#39;app\data_set.csv&#39;);<br>$file = fopen($path, &#39;r&#39;);<br><br>while(($row = fgetcsv($file, null, &#39;,&#39;)) !== false) {<br>    table::insert([<br>      &#39;name&#39; =&gt; $row[0]<br>      &#39;date&#39; =&gt; $row[1],<br>      &#39;time&#39; =&gt; $row[2]<br>    ])<br>}<br>fclose($file);<br></pre><p>2. And the second way is more efficient than the first approach. and that is, we can store data in a one single array and chunk it and insert it to the database as below,</p><pre>$path = storage_path(&#39;app\data_set.csv&#39;);<br>$file = fopen($path, &#39;r&#39;);<br>$data = [];<br>while(($row = fgetcsv($file, null, &#39;,&#39;)) !== false) {<br>    $data[] = [<br>      &#39;name&#39; =&gt; $row[0]<br>      &#39;date&#39; =&gt; $row[1],<br>      &#39;time&#39; =&gt; $row[2]<br>    ]<br>}<br>foreach (array_chunk($data, 1000) as $chunk) {<br>    table::insert($chunk);<br>}<br><br><br>fclose($file);</pre><p>This approach would be lot faster but it’s not memory efficient as it will exceed the memory limit.</p><p>3. So, this 3rd step is lot faster and a better approach than the first two approaches as this will again use the chunking.</p><p>create a helper file ,<strong> ArrayHelper.php</strong></p><pre>namespace App\Helpers<br><br>class ArrayHelper {<br><br>    public static chunkFile(string $path, callable $generatorFunction, int $chunkSize) {<br>    <br>          $file = fopen($file, &#39;r&#39;);<br>          $data = [];   <br><br>          for($i=1 ; ($row = fgetcsv($file, null, &#39;,&#39;)) !== false ; $i++) {<br>            $data[] = $generatorFunction($row);<br><br>            if ($i % $chunkSize == 0) {<br>                yield $data;<br>                $data = [];<br>            }<br>          }<br><br>          if (!empty($data)) {<br>              yield $data;<br>          }<br><br>          fclose($file);   <br><br>    }<br><br>}</pre><pre>Route::get(&#39;/&#39;, function() {<br><br>    $generateRow = function($row) {<br>        return [<br>          &#39;name&#39; =&gt; $row[0]<br>          &#39;date&#39; =&gt; $row[1],<br>          &#39;time&#39; =&gt; $row[2]<br>        ];<br>    }<br><br>    $path = storage_path(&#39;app\data_set.csv&#39;);<br><br>    // let&#39;s call the helper function now<br>    foreach (ArrayHelper::chunkFile($path, $generateRow, 1000) as $chunk) {<br>        table::insert($chunk)<br>    }<br><br><br>})</pre><p>This approach might save lot of time but there is another solution that you might love.</p><p>4. This approach is specific for the MySQL and MariaDB and this is going to take only few seconds to run. And that is LOAD DATA INFILE . if the file is in the client side, we can use LOAD DATA LOCAL INFILE`</p><pre>$path = storage_path(&#39;app\data_set.csv&#39;);<br>$escapedPath = DB::getPdo()-&gt;quote($path);<br>DB::statement(<br>&quot;<br>LOAD DATA LOCAL INFILE {$escapedPath}<br>INTO TABLE data<br>FIELDS TERMINATED BY &#39;,&#39;<br>LINES TERMINATED BY &#39;\\n&#39;<br>(name, @date_var, time)<br>set date = STR_TO_DATE(@date_var, &#39;%m/%d/%y&#39;)<br>&quot;<br><br>)</pre><p>if we’re going to use this LOAD DATA INFILE, there are some changes that you need to done in the database as well as laravel side like below,</p><p>if you’re using xampp,</p><p>go to Mysql config and set <strong>`local_infile = 1`</strong></p><p>and in laravel, database -&gt; mysql section -&gt; options</p><p>add PDO::MYSQL_ALTER_LOCAL_INFILE = true</p><p>if those didn’t work, run the below query in mysql</p><p>GRANT FILE ON *.* “root”@”localhost”</p><p>And that’s it about the Bulk insertion</p><p>Cheers !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55aeaeaf4c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphic relationships in Laravel and their use cases]]></title>
            <link>https://medium.com/@ashameemeduma/polymorphic-relationships-in-laravel-and-their-use-cases-04396a64a608?source=rss-eb5ef941055d------2</link>
            <guid isPermaLink="false">https://medium.com/p/04396a64a608</guid>
            <category><![CDATA[laravel-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[develpment]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[laravel-framework]]></category>
            <dc:creator><![CDATA[Rishni Meemeduma]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 23:01:08 GMT</pubDate>
            <atom:updated>2024-11-18T23:01:08.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMLkqnasYKPHjC9k4RQZXg.jpeg" /></figure><p>In software development, it’s common to encounter models that belong to multiple entities. A great example is <em>comments</em>. Take an application like Facebook, for instance: comments can be associated with posts, stories, or videos while maintaining the same structure. This behavior is an excellent illustration of <strong>polymorphism</strong> in action.</p><p>In this article, we will explore polymorphic relationships in Laravel, delve into how they work, and discuss the various use cases where they shine the most.</p><h3><a href="https://laravel.com/docs/11.x/eloquent-relationships#polymorphic-relationships">Polymorphic Relationships</a></h3><p>A polymorphic relationship lets one model be connected to multiple other models using a single setup. For example, if you’re building an app where users can share blog posts and videos, a <strong>Comment</strong> model can be linked to both <strong>Post</strong> and <strong>Video</strong> models. This means users can comment on either posts or videos without needing separate comment systems.</p><p><strong><em>One to One (Polymorphic)</em></strong></p><p>A one-to-one polymorphic relationship is like a regular one-to-one relationship, but with a twist: the child model can be linked to more than one type of parent model using just one connection. For example, a <strong>Profile</strong> could belong to either a <strong>User</strong> or an <strong>Admin</strong>, all through the same relationship setup.</p><p>let’s examine the table structure:</p><pre>admin<br>    id - integer<br>    name - string<br> <br>users<br>    id - integer<br>    name - string<br> <br>profile<br>    id - integer<br>    avatar- string<br>    profileable_id - integer<br>    profileable_type - string</pre><p>The profileable_id column will contain the id values of admin or users. While the profileable_type column will contain the class name of the parent users , admin models. it’s either <em>App\Models\Users</em> or <em>App\Models\Admin</em></p><p>Now, let check the models</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphTo;<br> <br>class Profile extends Model<br>{<br>    /**<br>     * Get the parent profileable model (user or admin).<br>     */<br>    public function profileable(): MorphTo<br>    {<br>        return $this-&gt;morphTo();<br>    }<br>}<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphOne;<br> <br>class Users extends Model<br>{<br>    /**<br>     * Get the users profile.<br>     */<br>    public function profile(): MorphOne<br>    {<br>        return $this-&gt;morphOne(Profile::class, &#39;profileable&#39;);<br>    }<br>}<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphOne;<br> <br>class Admin extends Model<br>{<br>    /**<br>     * Get the admin profile.<br>     */<br>    public function profile(): MorphOne<br>    {<br>        return $this-&gt;morphOne(Profile::class, &#39;profileable&#39;);<br>    }<br>}</pre><p><strong><em>One to Many (Polymorphic)</em></strong></p><p>A one-to-many polymorphic relationship is like a regular one-to-many relationship, but with a difference: the child model can be linked to multiple types of parent models using one setup. For example, a <strong>Comment</strong> model can belong to either a <strong>Post</strong> or a <strong>Video</strong>, allowing users to leave comments on both without needing separate comment systems</p><p>let’s examine the table structure required to build this relationship:</p><pre>posts<br>    id - integer<br>    title - string<br>    body - text<br> <br>videos<br>    id - integer<br>    title - string<br>    url - string<br> <br>comments<br>    id - integer<br>    body - text<br>    commentable_id - integer<br>    commentable_type - string</pre><p>Next, Model structure</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphTo;<br> <br>class Comments extends Model<br>{<br>    /**<br>     * Get the parent commentable model (posts or vidoes).<br>     */<br>    public function commentable(): MorphTo<br>    {<br>        return $this-&gt;morphTo();<br>    }<br>}<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphOne;<br> <br>class Videos extends Model<br>{<br>    /**<br>     * Get the video comments.<br>     */<br>    public function comments(): MorphMany<br>    {<br>        return $this-&gt;morphMany(Comments::class, &#39;commentable&#39;);<br>    }<br>}<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphOne;<br> <br>class Posts extends Model<br>{<br>    /**<br>     * Get the post comments.<br>     */<br>    public function comments(): MorphMany<br>    {<br>        return $this-&gt;morphMany(Comments::class, &#39;commentable&#39;);<br>    }<br>}</pre><p><strong><em>Many to Many (Polymorphic)</em></strong></p><p>Many-to-many polymorphic relationships let multiple models share a common relationship with another model. For example, both a <strong>Post</strong> and a <strong>Video</strong> can have tags, and those tags are stored in a single table. This setup allows you to manage unique tags that can be linked to either posts or videos, keeping things organized and flexible.</p><p>let’s examine the table structure required to build this relationship:</p><pre><br>posts<br>    id - integer<br>    name - string<br> <br>videos<br>    id - integer<br>    name - string<br> <br>tags<br>    id - integer<br>    name - string<br> <br>taggables<br>    tag_id - integer<br>    taggable_id - integer<br>    taggable_type - string</pre><p>Now, let check models</p><pre>&lt;?php<br> <br>namespace App\Models;<br> <br>use Illuminate\Database\Eloquent\Model;<br>use Illuminate\Database\Eloquent\Relations\MorphToMany;<br> <br>class Post extends Model<br>{<br>    /**<br>     * Get all of the tags for the post.<br>     */<br>     public function tags(): MorphToMany<br>    {<br>        return $this-&gt;morphToMany(Tag::class, &#39;taggable&#39;);<br>    }<br>}<br><br>class Tag extends Model<br>{<br>    /**<br>     * Get all of the posts that are assigned this tag.<br>     */<br>    public function posts(): MorphToMany<br>    {<br>        return $this-&gt;morphedByMany(Post::class, &#39;taggable&#39;);<br>    }<br> <br>    /**<br>     * Get all of the videos that are assigned this tag.<br>     */<br>    public function videos(): MorphToMany<br>    {<br>        return $this-&gt;morphedByMany(Video::class, &#39;taggable&#39;);<br>    }<br>}</pre><p><strong><em>Custom Polymorphic Types</em></strong></p><p>By default, Laravel saves the full class name of the related model (like App\Models\Post or App\Models\Video) in the commentable_type column to identify the type of model a comment belongs to.</p><p>However, if you want to simplify this and avoid saving full class names in the database — for example, just save post or video instead—you can customize this behavior. This makes the database cleaner and less tied to the internal structure of your application.</p><p>You can do this by defining a <strong>morph map</strong>, which tells Laravel to use shorter, custom names instead of full class names.</p><pre>use Illuminate\Database\Eloquent\Relations\Relation;<br><br>class AppServiceProvider extends ServiceProvider<br>{<br>    public function boot()<br>    {<br>        Relation::enforceMorphMap([<br>            &#39;post&#39; =&gt; App\Models\Post::class,<br>            &#39;video&#39; =&gt; App\Models\Video::class,<br>        ]);<br>    }<br>}</pre><p>In this example:</p><ul><li>The post key maps to the App\Models\Post class.</li><li>The video key maps to the App\Models\Video class.</li></ul><p>This will ensure that the commentable_type column in your database stores post or video instead of the fully qualified class names.</p><p>common usage,</p><pre>use App\Models\Post;<br>use App\Models\Video;<br>use App\Models\Comment;<br><br>// Attach a comment to a post<br>$post = Post::find(1);<br>$post-&gt;comments()-&gt;create([<br>    &#39;body&#39; =&gt; &#39;This is a comment on a post&#39;,<br>]);<br><br>// Attach a comment to a video<br>$video = Video::find(1);<br>$video-&gt;comments()-&gt;create([<br>    &#39;body&#39; =&gt; &#39;This is a comment on a video&#39;,<br>]);<br><br>// fetching comments<br>// Get all comments for a post<br>$postComments = Post::find(1)-&gt;comments;<br><br>// Get all comments for a video<br>$videoComments = Video::find(1)-&gt;comments;<br><br>// accessing the parents model<br>$comment = Comment::find(1);<br>$parent = $comment-&gt;commentable; // Returns the related Post or Video model</pre><p>Thank you !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04396a64a608" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>