ismaile

ismaile

Member Since 2 Years Ago

Experience Points
70,020
Total
Experience

4,980 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
445
Lessons
Completed
Best Reply Awards
41
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 15
70,020 XP
Jul
08
18 hours ago
Activity icon

Replied to How To Format Min And Max Date In Laravel

You should use minDate and maxDate. Here is the documentation for jQuery date time picker: https://xdsoft.net/jqplugins/datetimepicker/#mindate if that's the one you use.

$('.leaveDate').datetimepicker({
   format: 'MM/DD/YYYY',
    locale: 'en',
    minDate: '2020/01/01',
    maxDate: '2020/12/31'
});
$('.dobDate').datetimepicker({
   format: 'MM/DD/YYYY',
    locale: 'en',
    maxDate: (new Date()).toString()
  });
Activity icon

Awarded Best Reply on Query Result From Two Tables Into One Collection

Here is an option using union:

$drawing_query = Drawing::where('published', 1)->select(['name', 'creation_date']);
$animations_query = Animations::where('published', 1)->select(['name', 'creation_date']);

$creations = $drawing_query->union($animations_query)->orderBy('creation_date', 'desc')->limit(4)->get();

Please note that I am selecting the same columns for both queries. creation_date is the only mandatory column since it is used to order the results. I have added a column called name as an example.

Activity icon

Replied to Query Result From Two Tables Into One Collection

Here is an option using union:

$drawing_query = Drawing::where('published', 1)->select(['name', 'creation_date']);
$animations_query = Animations::where('published', 1)->select(['name', 'creation_date']);

$creations = $drawing_query->union($animations_query)->orderBy('creation_date', 'desc')->limit(4)->get();

Please note that I am selecting the same columns for both queries. creation_date is the only mandatory column since it is used to order the results. I have added a column called name as an example.

Activity icon

Awarded Best Reply on Production.ERROR: Object Of Class StdClass Could Not Be Converted To String {"userId":466,"exception":"[object] (ErrorException(code: 0)

At first glance, where('appraisal_identity_id', $identities) , in the last DB statement, might be the root of the issue.

Indeed, $identities is an object. You can try replacing it with:

where('appraisal_identity_id', $identities->id)`

As as side note, since $identities represents only the first value, I would call the variable $identity

Activity icon

Replied to How To Add Localization For Existing Laravel With 100s Of Routes

You have various options:

Activity icon

Replied to Production.ERROR: Object Of Class StdClass Could Not Be Converted To String {"userId":466,"exception":"[object] (ErrorException(code: 0)

At first glance, where('appraisal_identity_id', $identities) , in the last DB statement, might be the root of the issue.

Indeed, $identities is an object. You can try replacing it with:

where('appraisal_identity_id', $identities->id)`

As as side note, since $identities represents only the first value, I would call the variable $identity

May
11
1 month ago
Activity icon

Awarded Best Reply on Binary Tree From 1 To 10 In All Traversals The Same Result

Hi,

You are not doing anything wrong. However, nothing says you can't reuse digits. This means, if the root node has a value of 1, then the leftmost should also have a value of 1. Here is an example with digits from 1 to 3 to show you what I mean:

               1
              /  \
            2     2
           /        \
         3           3
        /             \
      2                2
     /                   \
   1                      1

You can even do it like this:

               1
              /
            2
           /
         3
        /
      2
     /
   1

or like this:

                1
                  \
                   2
                     \
                      3
                        \
                         2
                          \
                           1

For all traversals, the result is 1-2-3-2-1.

So, there is a symmetry to the node with a value of 3. It can be extended to 10 and numbers could be switched as long as a symmetry is kept. Here are other examples: 3-2-1-2-3 or 2-1-3-1-2

Activity icon

Replied to Binary Tree From 1 To 10 In All Traversals The Same Result

Hi,

You are not doing anything wrong. However, nothing says you can't reuse digits. This means, if the root node has a value of 1, then the leftmost should also have a value of 1. Here is an example with digits from 1 to 3 to show you what I mean:

               1
              /  \
            2     2
           /        \
         3           3
        /             \
      2                2
     /                   \
   1                      1

You can even do it like this:

               1
              /
            2
           /
         3
        /
      2
     /
   1

or like this:

                1
                  \
                   2
                     \
                      3
                        \
                         2
                          \
                           1

For all traversals, the result is 1-2-3-2-1.

So, there is a symmetry to the node with a value of 3. It can be extended to 10 and numbers could be switched as long as a symmetry is kept. Here are other examples: 3-2-1-2-3 or 2-1-3-1-2

Feb
02
5 months ago
Activity icon

Awarded Best Reply on How To Update Cookies At Laravel 5.6

A composer update should be enough.

Indeed, here is the composer file for Laravel framework 5.6: https://github.com/laravel/framework/blob/5.6/composer.json

For each Symfony dependency, you can see there is: ~4.0 for the versioning. This translates to >=4.0 <5.0.0 as described here: https://getcomposer.org/doc/articles/versions.md#tilde-version-range-

So, you should get Symfony version 4.4 after a composer update and you should be good to go.

PS: I don't recommend at all to update Symfony directly. Laravel uses Symfony components a lot and you might get inconsistencies by using an incompatible version.

Jan
31
5 months ago
Activity icon

Awarded Best Reply on Custom Eloquent Query Scope With Pivot

@musa11971

I don't think this is possible. attach expects the id and the pivot table values.

You can embed your logic in a method instead:

public function addALibraryBeingProcessed($library_id)
{
    $this->library()->attach($library_id, ['status' => 'being_processed']);
}

PS: On a side note, regarding the naming, I would change library to libraries for the methods library and libraryBeingProcessed since we are expecting many libraries per user.

Jan
30
5 months ago
Activity icon

Replied to How To Save A BelongsToMany Relationship?

To start with, you can remove this code:

$insert = array(                        
    'code_insert' => $code_insert[$count],
    'quality'     => $quality[$count]
);

Regarding the cleaner way to get the same result, let's think of it in 2 ways:

  • Cleaning the solution itself: I don't have the whole context but your code looks somehow similar to a To-do list with an Add task or + button. Instead of tasks, you have tools. The good news is you can find so many articles and lessons about To-do lists. Anyway, the quick answer is to separate things. You can use JavaScript to add existing tools to the list. Tools would appear in a multiple select with autocomplete and the user can select existing tools. If the tool doesn't exist, it could be created first along with its associated "insert". You would either do the creation in the same page with Ajax or in another page if you want to keep things separate. In this case, a link to the tool creation page would always be there if a tool doesn't exist yet. Once the list of tools is ready, the user can submit the list of tools so that they are attached to the piece.
  • Cleaning the code: as of now, the store method is rather big, so you can start by looking at thin controllers: https://laraveldaily.com/taylor-otwell-thin-controllers-fat-models-approach/

Hope this helps.

Activity icon

Replied to How To Show Data From Many To Many?

@haritz

The following code should work:

App\League::whereDoesntHave('users', function($query) {
    $query->where('users.id',auth()->id());
})->withCount('users')->get();

auth()->id() is a shorter version to get the auth user id.

Activity icon

Replied to How To Update Cookies At Laravel 5.6

A composer update should be enough.

Indeed, here is the composer file for Laravel framework 5.6: https://github.com/laravel/framework/blob/5.6/composer.json

For each Symfony dependency, you can see there is: ~4.0 for the versioning. This translates to >=4.0 <5.0.0 as described here: https://getcomposer.org/doc/articles/versions.md#tilde-version-range-

So, you should get Symfony version 4.4 after a composer update and you should be good to go.

PS: I don't recommend at all to update Symfony directly. Laravel uses Symfony components a lot and you might get inconsistencies by using an incompatible version.

Activity icon

Replied to Custom Eloquent Query Scope With Pivot

@musa11971

I don't think this is possible. attach expects the id and the pivot table values.

You can embed your logic in a method instead:

public function addALibraryBeingProcessed($library_id)
{
    $this->library()->attach($library_id, ['status' => 'being_processed']);
}

PS: On a side note, regarding the naming, I would change library to libraries for the methods library and libraryBeingProcessed since we are expecting many libraries per user.

Activity icon

Awarded Best Reply on How To Create Composer Package For Laravel?

Did you take a look at the related doc for Package development ?

https://laravel.com/docs/6.x/packages

Activity icon

Awarded Best Reply on How To Show Data From Many To Many?

Here is a code suggestion:

App\League::withCount('users')->get();

In your foreach, you can access the count with:

{{$league->users_count}}
Activity icon

Replied to How To Show Data From Many To Many?

Here is a code suggestion:

App\League::withCount('users')->get();

In your foreach, you can access the count with:

{{$league->users_count}}
Activity icon

Replied to How To Create Composer Package For Laravel?

Yes, the doc reference I sent you is all about packages for Laravel.

If you are new to Laravel, you should also read: https://laravel.com/docs/6.x/providers and https://laravel.com/docs/6.x/container to understand what's going on.

Also, if projectA uses package1 and you are working on it locally, the following link might help you to define package1 as a local dependency of projectA: https://laravel-news.com/developing-laravel-packages-with-local-composer-dependencies

Activity icon

Replied to How To Send Notification Like "App Updated" Or "You Have A New User" ?

I think you should watch this video to get started: https://laracasts.com/series/laravel-6-from-scratch/episodes/47. It is about database notifications. Then if you need more details, you can look at the documentation: https://laravel.com/docs/6.x/notifications

Activity icon

Replied to How To Create Composer Package For Laravel?

Did you take a look at the related doc for Package development ?

https://laravel.com/docs/6.x/packages

Activity icon

Replied to How To Update Cookies At Laravel 5.6

I think you should take a look at config/session.php

There you have 2 settings:

  • 'same_site' => null,
  • 'secure' => env('SESSION_SECURE_COOKIE', false),

same_site should accept a value of "none". I would create a dedicated env variable for this.

Laravel uses Symfony components and " 'None' same site" has been added to Symfony after Laravel 5.6. Here is the PR from May 2019: https://github.com/symfony/symfony/pull/31475. However, the PR is applied to the Symfony version 3.4 and Laravel 5.6 uses Symfony ~4.0. So, you should be good to go.

Here is the session configuration file: https://github.com/laravel/laravel/blob/master/config/session.php

Jan
29
5 months ago
Activity icon

Replied to How To Save A BelongsToMany Relationship?

I think your issue comes from this line:

$tools = Tool::insert($tool_data);

Indeed, Tool::insert($tool_data); is going to return true which resolves to 1.

The quickest way to deal with this is to remove that line and replace:

$tool_data[] = $tool;

with:

$tools[] = Tool::insertGetId($tool);
Activity icon

Replied to How To Save A BelongsToMany Relationship?

Using $tools seems more appropriate. Besides, if you don't want to lose existing relationships, then attach is the method to use. In this case, yes, you can try:

$piece->tools()->attach($tools);

If you have any issue, try to insert dd($tools) before the attach call to make sure $tools has the right format.

Activity icon

Replied to How To Save A BelongsToMany Relationship?

Edited to stay relevant [since the initial post got updated with new information]

Here is what's most likely happening with your code. In $piece->tools()->sync($request->$tools);, $request->tools is null. So, sync will detach any existing relationships. But if there are no existing relationships, it won't have any effect. In any case, no errors.

Now, 2 things to keep in mind:

  • If the tools already exist, you should directly pass an array of ids to the sync method as described in the documentation: https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships. Besides, when debugging, you should focus on what you are passing to the sync method. In this case, dd($request->tools) would returnnull since $request properties come from the view inputs and there is no tools input.
  • sync has a special behaviour, "Any IDs that are not in the given array will be removed from the intermediate table" as specified in the documentation. If you need to keep previous relationships, you should reach for attach.

I hope this clarifies. So, there are 2 next steps:

  • Deciding if you use sync or attach
  • Modifying the data passed to the sync or attach method
Activity icon

Replied to How To Save A BelongsToMany Relationship?

Do you get any error ? Could you please share your form code ?

Activity icon

Awarded Best Reply on Global Objects? Shared Relationships? Not Sure How To Describe This

@kimg

You should look at eager loading and lazy eager loading when you query your fanfics. It turns out, the documentation specifies an example with books for lazy eager loading.

For the bonus points, you should definitely look at nested eager loading, it is mentioned in the eager loading part of the documentation. You would end up doing something like:

App\Fanfic::with('user.comments')->get();
// or if you use pagination for fanfics, this is an example with 5 results per page
// App\Fanfic::with('user.comments')->paginate(5);

Hope this clarifies

https://laravel.com/docs/6.x/eloquent-relationships#eager-loading https://laravel.com/docs/6.x/eloquent-relationships#lazy-eager-loading

Activity icon

Replied to Global Objects? Shared Relationships? Not Sure How To Describe This

@kimg

You should look at eager loading and lazy eager loading when you query your fanfics. It turns out, the documentation specifies an example with books for lazy eager loading.

For the bonus points, you should definitely look at nested eager loading, it is mentioned in the eager loading part of the documentation. You would end up doing something like:

App\Fanfic::with('user.comments')->get();
// or if you use pagination for fanfics, this is an example with 5 results per page
// App\Fanfic::with('user.comments')->paginate(5);

Hope this clarifies

https://laravel.com/docs/6.x/eloquent-relationships#eager-loading https://laravel.com/docs/6.x/eloquent-relationships#lazy-eager-loading

Activity icon

Replied to How Do Delete Cached Laravel Config File Manually

You can call artisan commands programmatically. This should work:

Artisan::call('config:clear');

https://laravel.com/docs/master/artisan#programmatically-executing-commands

Activity icon

Replied to Custom Eloquent Query Scope With Pivot

@musa11971 Sorry, I have been a bit quick to respond and didn't pay attention. I have removed the answer since it was not relevant. Local scopes are used to filter a model not a relation.

This should work:

public function libraryBeingProcessed()
    {
        return $this->library()->wherePivot('status', 'being_processed');
    }

And you can use it like so:

$user->libraryBeingProcessed();
Activity icon

Awarded Best Reply on What Is The Best Way To Paginate A Collection?

What about:

Tag::where('name', $tag)->firstOrFail()->articles()->paginate(3)

Here we have parentheses after articles. The thing is:

  • Without parentheses, Tag::where('name', $tag)->firstOrFail()->articles returns a collection
  • With parentheses, Tag::where('name', $tag)->firstOrFail()->articles() returns a BelongsToMany instance

There is no paginate method in the Collection class whereas there is a paginate method for the BelongsToMany class.

Activity icon

Replied to Laracasts - Wrong Course Complete Calculation

I just took a look once again at the video playlist.

There are 8 videos while it says 7 episodes at the top. This is a bug and you should contact @jeffreyway

Activity icon

Awarded Best Reply on How To Display Foreign Key Value As The Title Of A View Blade

@noblemfd

1- The quick fix is:

  <div>
    Current Appraisal: {{ $identities->appraisal_name }}
  </div>

Indeed, $identities is still an Eloquent model even though you used select. The difference is that the DB request selects one field so the model only has the selected field available.

I would rename the variable to $identity in the create method and in the view since there is only one identity here: you get the first one with the method first. I will use $identity from now on. So, to answer the first requirement, the create view should have this code:

  <div>
    Current Appraisal: {{ $identity->appraisal_name }}
  </div>

and the create method should have this code:

$identity = DB::table('appraisal_identity')->select('appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();

2- I guess you should pass $identity->id as a hidden input. In the create view file, you should have a form with:

<input type="hidden" name="appraisal_identity_id" value="{{ $identity->id }}">

In the create method, you should add the id to your select like so:

$identity = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();

and in the store method, you should uncomment your code:

//  $goal->appraisal_identity_id    = $request->appraisal_identity_id;
Activity icon

Replied to How To Display Foreign Key Value As The Title Of A View Blade

@noblemfd

1- The quick fix is:

  <div>
    Current Appraisal: {{ $identities->appraisal_name }}
  </div>

Indeed, $identities is still an Eloquent model even though you used select. The difference is that the DB request selects one field so the model only has the selected field available.

I would rename the variable to $identity in the create method and in the view since there is only one identity here: you get the first one with the method first. I will use $identity from now on. So, to answer the first requirement, the create view should have this code:

  <div>
    Current Appraisal: {{ $identity->appraisal_name }}
  </div>

and the create method should have this code:

$identity = DB::table('appraisal_identity')->select('appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();

2- I guess you should pass $identity->id as a hidden input. In the create view file, you should have a form with:

<input type="hidden" name="appraisal_identity_id" value="{{ $identity->id }}">

In the create method, you should add the id to your select like so:

$identity = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();

and in the store method, you should uncomment your code:

//  $goal->appraisal_identity_id    = $request->appraisal_identity_id;
Activity icon

Awarded Best Reply on How To Speed Up Search ( 1 Million Record ) PHP & MYSQL?

You should definitely look at indexes. If you perform some queries frequently, indexing the related fields would immediately reduce the response time.

You can think of indexes like ordering according to one or more fields. If you look for a word in an unordered dictionary, you would have to check for each page until you find the word. At best, the result is on the first page, at worst, it is in the last page you checked and it took a lot of time. Indexing puts some order so you can open it at the middle then jump to the first half or second half and so on.

By default, the id is usually the primary key and is indexed. However, you can index several keys.

https://laravel.com/docs/6.x/migrations#indexes

Jan
28
5 months ago
Activity icon

Replied to Laracasts - Wrong Course Complete Calculation

@frezno

There are 7 courses in "Code Katas with PHPUnit" and 114% appears to match with 8/7.

I guess there is a duplicate entry in the pivot table between users and videos. I would mark each video as incomplete to find the one causing the issue. Then, I would mark it as complete once again to go back to normal. You can do this for each video while keeping another tab open in your overview. This other tab could be refreshed multiple times throughout the process to check the evolution of the number of lessons completed.

Activity icon

Replied to What Is The Best Way To Paginate A Collection?

What about:

Tag::where('name', $tag)->firstOrFail()->articles()->paginate(3)

Here we have parentheses after articles. The thing is:

  • Without parentheses, Tag::where('name', $tag)->firstOrFail()->articles returns a collection
  • With parentheses, Tag::where('name', $tag)->firstOrFail()->articles() returns a BelongsToMany instance

There is no paginate method in the Collection class whereas there is a paginate method for the BelongsToMany class.

Activity icon

Awarded Best Reply on Laravel - XMLHttpRequest While Trying To Retrieve Data From Api Call Ajax

@rainieren

It seems like the package is now called: fruitcake/laravel-cors. If you ran: composer require barryvdh/laravel-cors, please remove it with: composer remove barryvdh/laravel-cors

Did you follow precisely these steps for https://www.rainierlaansite.test ?

  • Run composer require fruitcake/laravel-cors
  • Include \Fruitcake\Cors\HandleCors::class, in the $middleware array in app/Http/Kernel.php
  • Run php artisan vendor:publish --tag="cors"
  • Update paths in config/cors.php so that you have 'paths' => ['api/*'],

PS: please keep in mind that there are extra config parameters to add some security. You can start with setting allowed_origins to https://rainierlaan.test. Here you can find more information: https://github.com/fruitcake/laravel-cors#configuration

Activity icon

Replied to Laravel - XMLHttpRequest While Trying To Retrieve Data From Api Call Ajax

@rainieren

It seems like the package is now called: fruitcake/laravel-cors. If you ran: composer require barryvdh/laravel-cors, please remove it with: composer remove barryvdh/laravel-cors

Did you follow precisely these steps for https://www.rainierlaansite.test ?

  • Run composer require fruitcake/laravel-cors
  • Include \Fruitcake\Cors\HandleCors::class, in the $middleware array in app/Http/Kernel.php
  • Run php artisan vendor:publish --tag="cors"
  • Update paths in config/cors.php so that you have 'paths' => ['api/*'],

PS: please keep in mind that there are extra config parameters to add some security. You can start with setting allowed_origins to https://rainierlaan.test. Here you can find more information: https://github.com/fruitcake/laravel-cors#configuration

Activity icon

Awarded Best Reply on How To Specify Dynamic Input Fields Rows Based On User Type

Please try this:

var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};

Your initial code returns true but at the PHP level. To make sure, the code is "pasted" correctly to the frontend, you should be explicit. If your condition returns false, you would get in the frontend: var isHod = ;

Activity icon

Replied to How To Specify Dynamic Input Fields Rows Based On User Type

Please try this:

var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};

Your initial code returns true but at the PHP level. To make sure, the code is "pasted" correctly to the frontend, you should be explicit. If your condition returns false, you would get in the frontend: var isHod = ;

Activity icon

Awarded Best Reply on Remove Button Is Not Working In Dynamic Input Form

You are right. Here you go:

<script type="text/javascript">
    $(document).ready(function(){
        $('.addRow').on('click', function () {
            addRow();

        });

        function addRow() {
            var addRow = '<tr>\n' +
'  <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
'  <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
'  <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
'  <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
'   </tr>';
            $('tbody').append(addRow);
            addRemoveListener();
        };

        addRemoveListener();
    });

function addRemoveListener() {
    $('.remove').on('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{

                $(this).parent().parent().remove();

            }

        });
}
</script>

I embedded the code for setting the remove click listener in a function addRemoveListener. The function is called at load time to handle the first one. Then, the function is called within addRow so that the remove click listener is attached for each new row.

Activity icon

Replied to How To Speed Up Search ( 1 Million Record ) PHP & MYSQL?

You should definitely look at indexes. If you perform some queries frequently, indexing the related fields would immediately reduce the response time.

You can think of indexes like ordering according to one or more fields. If you look for a word in an unordered dictionary, you would have to check for each page until you find the word. At best, the result is on the first page, at worst, it is in the last page you checked and it took a lot of time. Indexing puts some order so you can open it at the middle then jump to the first half or second half and so on.

By default, the id is usually the primary key and is indexed. However, you can index several keys.

https://laravel.com/docs/6.x/migrations#indexes

Activity icon

Awarded Best Reply on ErrorException (E_WARNING) Creating Default Object From Empty Value

Your variable is missing an s. So to fix the error, you can use:

$items->content_id = $request->page;

However, since you only have one item. You'd better change all variables to $item

Activity icon

Replied to ErrorException (E_WARNING) Creating Default Object From Empty Value

Your variable is missing an s. So to fix the error, you can use:

$items->content_id = $request->page;

However, since you only have one item. You'd better change all variables to $item

Activity icon

Replied to Remove Button Is Not Working In Dynamic Input Form

You are right. Here you go:

<script type="text/javascript">
    $(document).ready(function(){
        $('.addRow').on('click', function () {
            addRow();

        });

        function addRow() {
            var addRow = '<tr>\n' +
'  <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
'  <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
'  <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
'  <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
'   </tr>';
            $('tbody').append(addRow);
            addRemoveListener();
        };

        addRemoveListener();
    });

function addRemoveListener() {
    $('.remove').on('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{

                $(this).parent().parent().remove();

            }

        });
}
</script>

I embedded the code for setting the remove click listener in a function addRemoveListener. The function is called at load time to handle the first one. Then, the function is called within addRow so that the remove click listener is attached for each new row.

Activity icon

Replied to Remove Button Is Not Working In Dynamic Input Form

You should use:

$('.remove').on

instead of:

$('.remove').live
Activity icon

Replied to Help With Php Artisan Queue:work

Queues could be confused with tasks since scheduled jobs could be queued first. However, they are actually different.

When you schedule a task, a cron job is involved: https://laravel.com/docs/6.x/scheduling

For queues, php artisan queue:work listens for any job. If there are no jobs in the queue, it will be handled immediately: https://laravel.com/docs/6.x/queues

Activity icon

Awarded Best Reply on Correctly Query A Pivot Table

Edited

There a many ways to do this:

  • Check the intersection between 2 Eloquent query results. The intersection between: App\User::find(1)->conversations->pluck('conversations.id') and App\User::find(2)->conversations->pluck('conversations.id). Here, array_intersect might help.
  • Give some sort of name to a conversation to identify it easily such as: 1_2 (starting with the smallest user id number). Information is duplicated but the query for an existing conversation between 2 users is made simple and straightforward.
  • Use the SQL way with query builders, here are 2 suggestions:

Option 1:

DB::table(function($q) {
            $q->select('conversation_user.conversation_id')->from('conversation_user')->where('conversation_user.user_id',1);
        },'authconversations')->join('conversation_user','authconversations.conversation_id','=','conversation_user.conversation_id')->where('conversation_user.user_id',2)->exists();

Here, I am using a sub query to retrieve all conversations for user 1. I assumed user 1 is the authenticated user, hence the naming authconversations, it could be changed. Then, I joined the result with the pivot table and restricted it to user 2 conversations.

Or to put it simply, we store user 1 conversations and perform a query on the result to check if one is matching with user 2.

I used exists at the end to shorten the query but it could be done with whereExists.

Option 2a:

DB::table('conversation_user as a')
            ->join('conversation_user as b', 'a.id', '!=','b.id')
            ->where([['a.user_id','=',1],['b.user_id','=',2]])
            ->whereColumn('a.conversation_id','b.conversation_id')
            ->exists();

Here, it is a self join. Think of a list of pivot entries 1,2,3,4 but associated with one another: 1-2, 1-3, 2-1. != prevents from having 1-1. If we find an entry with user id 1, user id 2, and the same conversation id, then there is a conversation between the users 1 and 2. Why do we bother checking that it is the same conversation id ? Well, the self join also joins unrelated conversations.

Option 2b:

DB::table('conversation_user as a')
            ->join('conversation_user as b', 'a.id', '<','b.id')
            ->where(function($q){
                $q->where([['a.user_id','=',1],['b.user_id','=',2]])
                ->orWhere([['a.user_id','=',2],['b.user_id','=',1]]);
            })
            ->whereColumn('a.conversation_id','b.conversation_id')
            ->exists();

Here, the join is more restrictive, < is used instead of !=. We get combinations instead of permutations. The benefit is that the join gets less results. If I have 1 - 2, I don't need 2 - 1. As a result, we use orWhere to check for either orders. Is it more performant than 2a ? Maybe. Even if we do add an 'orWhere', it is applied on a smaller data set. Performance tests would help to compare both options.

Activity icon

Awarded Best Reply on Many To Many - Attaching Multiple Records + Multiple Columns

@zaster Please try this:

$subjobs = SubJob::whereIn('id',$selected_sub_job_ids)
            ->select('id','qty','rate','description')
            ->get()
            ->keyBy('id')
            ->each(function($item,$key){
                $item["visibility"]=1;
                unset($item['id']);
            })->toArray();

$invoice->sub_jobs()->attach($subjobs);

Just to give you a sense of what's happening, here is what it would look like with some values:

$invoice->subjobs()->attach([
    1 => ['qty' => 10, 'rate' => 0.2, 'description' => 'Lorem 1'],
    2 => ['qty' => 12, 'rate' => 0.3, 'description' => 'Lorem 2'],
]);

Here is the related documentation, it mentions that attach and detach also accept arrays of IDs as input: : https://laravel.com/docs/6.x/eloquent-relationships#updating-many-to-many-relationships

Activity icon

Replied to Console Log Not Printing From Blade

@swimmer If nothing is happening, that means your code has not been executed.

To be 100% sure it is not executed, please try to modify temporarily your code like so:

debugger;
$('#add-to-cart-btn').on('click',(e)=>
        {
        debugger;
        console.log(e.target.getAttribute("data-id"));
        }

Then reload your page and click on the button while having the developer tool open. Does your code get paused in the debuggers ?

PS: once you solve this, your code should be modified because depending on where you click the target might the image. I should have thought about it. Here is a quick suggestion:

<script>
$('#add-to-cart-btn').on('click', (e) => {
    if (e.target.parentNode.tagName === 'BUTTON') {
        // Click caught by the image
        console.log(e.target.parentNode.getAttribute("data-id"));
    } else {
        // Click caught by the button
        console.log(e.target.getAttribute("data-id"));
    }
});
</script>