hondnl

hondnl

Member Since 2 Years Ago

Experience Points 16,170
Experience Level 4

3,830 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 151
Lessons
Completed
Best Reply Awards 1
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

21 Feb
3 weeks ago

hondnl left a reply on Caching API Resources

Sometimes I find the Laravel API resources a bit too much for what you need. The overhead alone and the amount of extra files you have to write.

You can easily write your own ... and extend the functionality.

$resource =function($item){



        $thumbnail = $item->image_id 
                    ? $item->image->map(function($image){
                        return [
                          thumbnail_path => $image->path
                        ]
                    })->all()
                    :null;


        return [
            'id' => $item->id,
            'title' => $item->title,
            'subtitle' => $item->subtitle,
            'thumbnail' => $thumbnail; 
        ];

});

$rows = Car:all();

return $rows->map($resource)->all();

hondnl left a reply on Best Way To Handle Huge Insertion In Laravel Considering Both Timeout And Memory Issue

It depends indeed if this a one time thing or you need to do this more often.

I once needed to import an cvs file with over 1.5 million rows,but i needed to join some columns or needed to apply some string fixes on some columns.

even reading the file in php made the system timeout. So I used an external program to split the cvs files into rows of 10.000. Use a naming convention like cvsname_part1.cvs Used a for loop to load each split csv file. Then I just loaded each file into the memory , created a collection and then chunked the rows to 500 each > creating a new insert collection. This way I could insert 500 rows at a time into mysql. Went fine and was faster then I though it would be...

Or you could take a look at mysql load data... then move the data after import to other tables the way you see fit.

LOAD DATA LOCAL INFILE '/home/user/dataset.csv' INTO TABLE tablename FIELDS TERMINATED BY ',' (col1, col2, col3, col4, col5);

18 Dec
3 months ago

hondnl left a reply on Multidimensional Array , Group By Keys And Unique Values

@LOSTDREAMER_NL - Yes , off course you are completely right, it is just strange there is not a macro for this.

->pluckByKeys ($level=1){

// loop level. $keys= array_keys($item);

// got keys ['name,age] pluck them

// create new collection.

})-;

Well untested , but will create a macro for it. There must be a reason why it is not in the base collection. Will find out soon enough ;)

hondnl left a reply on Multidimensional Array , Group By Keys And Unique Values

@LOSTDREAMER_NL - Just as an interesting testcase , could we do this, just with laravel collections?

hondnl left a reply on Multidimensional Array , Group By Keys And Unique Values

@LOSTDREAMER_NL - Not really satisfying , is it ? It does not make this code any more efficient. Is there really not way to use groupBy , to achieve what I want ? I cannot imagine that I am the only one wanting this with my collections.

hondnl started a new conversation Multidimensional Array , Group By Keys And Unique Values

We got this array :

  $input =[
            ['name' =>'John McClane','age'=>'40' ],
            ['name' =>'John McClane','age'=>'50' ],
            ['name' =>'Hans Gruber','age'=>'40' ],
            ['name' =>'Hans Gruber','age'=>'50' ],
            ['name' =>'Holly McClane','age'=>'20' ],
            ['name' =>'Holly McClane','age'=>'49' ],
        ];

We want the output to be :

$output =[
            'name' => [
                'John McClane',
                'Hans Gruber',
                'Holly McClane'
            ],
            'age' =>[
                '40',
                '50',
                '20',
                '49'
            ]
        ];

We can do this in plain PHP with :

 foreach($input as $arr){
            $keys = array_keys($arr);
            foreach ($keys as $key) {
                $output[$key] =  array_unique(array_column($input, $key));
            }
        }

How would one do this with laravel collections?

12 Oct
5 months ago

hondnl left a reply on Scheduler Running With Delay (not On Time)

What part of the script depleted your entropy? You have a big random hash generator?

Thanks for the update , good to know...

03 Oct
5 months ago

hondnl left a reply on Cast ROUNDed Value To Decimal

I think we need some more info, it is not really clear what the problem is.

Since you want to order results in javascript ( frontend) , show us what your api/backend is giving you.

What you might be looking for is sorting integers in javascript once you got the results on the frontend.

var arr = [2,9999, 111.05, 1.05,1,00001]
arr.sort(function(a, b){return a-b;});

Good luck!

hondnl left a reply on Scheduler Running With Delay (not On Time)

@Charrua , @Cronix :

haha so recognizable , breaking your brain on an issue that is actually out of your reach. Finally contacting support and it magically disappears , while they state they cannot find the issue and you feel like an idiot.

Most of the time the guy had a big oops moment and does not want his boss to know and fixes it in silent.

I hope the guy want to tell us the story. Was it a bug in centos ( fixed with an update)? was it a badly configured VM ? Did it really resolve itself, what did update?

One of the reasons I get dedicated servers for my projects, when I f*ck up , at least I know It was me and not some external force.

If you really search for them , they are not that expensive. A bit of a learning curve , but the amount of documentation available to setup a healthy server is staggering.

Good luck and let us know what you found out.

hondnl left a reply on Scheduler Running With Delay (not On Time)

Is your hardware clock set to the same as your php/system time ?

hwclock --show

If at all possible on your setup , let's try the most simple tip we IT people always give. Put it off and on again....

/sbin/service crond stop
 /sbin/service crond start

If not on production , restart the server even.

If I remember correctly the hardware clock is set on server shutdown.

I really don't think your problem will be solved by above , but I have seen weirder things getting solved just by a reboot.

Also , check if there are not mulitple instances of cron are running and that they are setup correctly ( daily.cron set wrong?)

Good luck! would love to hear what the problem was if someone finds it

16 Aug
7 months ago

hondnl started a new conversation Polymorphic Tables, But Different.

Hi ,

Let's say we have 3 tables : titles,movies,tv_shows

  Schema::create('titles', function (Blueprint $table) {
            $table->increments('id'); // referenced as t_id
            $table->string('name');
            $table->tinyInteger('category');
            $table->unsignedSmallInteger('year')->index();
            $table->timestamps();
        });
   Schema::create('movies', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('t_id')->unique(); // titles id

           // extra columns
            $table->smallInteger('runtime')->nullable();
            $table->string('genres')->nullable();
            $table->tinyInteger('rating')->nullable();
            $table->timestamps();
        });
   Schema::create('tv_shows', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('t_id')->unique(); // titles id

        //  Extra columns
            $table->string('lang',50)->nullable()->index();
            $table->string('status',50)->nullable()->index();
            $table->smallInteger('runtime')->nullable();
            $table->date('first_aired')->nullable();
            $table->string('genres')->nullable();
            $table->string('url')->nullable();
            $table->unsignedTinyInteger('rating')->nullable();
            $table->unsignedInteger('network_id')->nullable()->index();
            $table->text('plot')->nullable();
            $table->smallInteger('season_type')->nullable();
            $table->timestamps();
        });

the titles category , is set as : 1=movie , 2=tv show We insert two titles into our db. One is a movie , the other is a tv show, so : category =1 && category= 2

Now ideally I would want something like this.

$titles = App\Title::with('info')->get();

foreach ($titles as $title) {

    // Where Title 1 ( movie) would give the row from table movies.
   // Where Title 2 ( tv show) would give the row from table tv_shows
    
     dump($title->info);
}

So that if you take a look at https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations the type would be the titles.category ( movie or tv show) and the id would be the t_id ( titles.id).

Is this achievable with laravel ?

Thanks

20 Mar
11 months ago

hondnl started a new conversation Laravel Schema Builder : Creating A Binary(16) Column

Using Laravel 5.5 and Mysql (10.1.19-MariaDB)

For a md5 hash I want a binary(16) column. Let's call the colum url_hash

When using :

$table->binary('url_hash');

it will give me a BLOB column.

source : https://laravel.com/docs/5.5/migrations#creating-columns

I have seen all kind of hacks or plugins around the web for this , but what is the most simple one without any external plugins that could break on the next update?

Cheers

06 Oct
1 year ago

hondnl left a reply on Get Value From Multidimensional Collection

Well I found this ....

$collect->pluck('foobar')->filter()->first()

But it feels a bit over the top to just check if a key exists and returning the value or null.

Anyone got other idea's?

or I am just getting back to if/else statements.

hondnl started a new conversation Get Value From Multidimensional Collection

Let's say we have :

$collection;
Illuminate\Support\Collection {#312
  #items: array:20 [
    "id" => 1
    "externals" => {#314
      +"anothertypeofid": 2
      +"evenAnother": 3
      +"foobar": 4
      }
    ]
    }

Is there a way to get foobar without checking first if it exists in the collection. and just return null if it does not.

// you got.
$collection->get('id');   // Will return null if it does not exits.

//  But you cannot do 
$collection->get('externals.foobar');   

What would be the fastest way to accomplish this ?

03 Oct
1 year ago

hondnl left a reply on Get First Collection Item Column

@Cronix

Would

if( $results->count() == 1){

Not solve this issue?

hondnl left a reply on Get First Collection Item Column

@36864 : thanks for answering, you got me on the right track.

I think I finally figured out some basic principles.. I just had to dive into Collection.php

I could do :

  $results->first()->t_id

It will loop over the array and immediately returns.

foreach ($array as $item) {
                return $item;
            }

but also

$results->get(0)->t_id;

this will do a basic array_key_exists and then returns the key.

All clear now, thanks

hondnl started a new conversation Get First Collection Item Column

Hi,

Let's say we got the following ''' $results =DB::table('table') ->select('t_id') ->where('foo','=','bar) ->get();

/** $results : Illuminate\Support\Collection {#106 #items: array:1 [ 0 => {#621 +"t_id": 1 } ] } **/

if( $result->count() == 1){

// Here is the problem... How do I return the t_id ? // the helper function has : array_get('0.t_id') .. but on collections?

return $result->get(???);

} .... /// else do something totally different.


How do I get the t_id from the first array in a Eloquent way?
01 Oct
1 year ago

hondnl started a new conversation Save() Update On Foreign Key.

Hi ,

Schema::create('titles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
Schema::create('title_updates', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('t_id')->unique();
            $table->string('title_source')->nullable();
            $table->dateTime('title_updated')->nullable();

        });
MODEL :Title
public function TitleUpdates()
    {
        return  $this->hasOne(TitleUpdate::class ,'t_id' );
    }
$title = new Title();
$titleUpdate =new TitleUpdate();

Let's say there is already a title in table titles. id =1 , name =test.

$title->id = 1;
$title->TitleUpdates()
    ->save(
         $this->titleUpdate->fill([
                 "title_source" => "foo",
               "time_updated" => "bar"
    ]
   )

How do I make the above update if the row with title_updates already contains a row with t_id =1 ? Now it just creates a new row.. creating an error ( unique key). Is there something in the model TitleUpdate that I can set ?

29 Sep
1 year ago

hondnl started a new conversation Use Migration BluePrints To Include Or Exclude Columns.

Hi , I was wondering if someone already made a nice extension/macro/provider for laravel that makes it more easy to exclude columns without querying the database for the columns.

You can use: select ( 'column1,'column2','column3','column4' ...) But what if you want all columns but want to exclude column 2, you have to write all the columns except column 2.

The current options are :

  1. Except .https://laravel.com/docs/5.4/collections#method-except This will just get ALL columns and then remove it after the query.

  2. Build a trait that fetches the columns and compares it to the one you don't want. getSchemaBuilder()->getColumnListing and then use a function like

select(array_diff($this->getTableColumns(), YOUR COLUMNS))

but this uses a query to fetch the columns. So bad practice.

  1. The one I am looking for : Use the migration BluePrints.

Would be great when you are migrating , a static file/class with arrays is build with the column names/types. Then build a trait that fetches the columns from this array (no query!) and does the same as in option 2.

With a nice macro you would have a new method, Something like this.

Model::selectExclude('description')->get();

05 Sep
1 year ago

hondnl left a reply on Saving Multiple Data To DB

First of all , markup code https://help.github.com/articles/creating-and-highlighting-code-blocks/

If I get this right , your request array will be something like this.

$input = $request->all();

[
  'name' = [
      'name1' 
     'name2'
   ],
  'img' [
    'image1',
   'image2'
  ]
]

You could just make an new collection/array.. let's keep it simple.

$inputArray =[];
foreach($input['name'] as $key=>$name){

  if( $input['img'][$key]){

     $fileNameToStore =.do your filesave...
 }

   $inputArray[]=[
        'name'  =>$name,
      'img =>$filenameTostore
    ]

}

$info = new Info //?? a model?


$info->create($inputArray);

Take a look at collections in laravel doc, since request is aready a collection.

hondnl left a reply on How To Delete Multiple Records Using Laravel Eloquent

gmanish his answer is the best one... Remember ,always check how many queries you run...

His is just one query.. the other ones are multiple queries.

You could also do this with the builder if you wanted to delete the products with a list of userid's

DB::table('products')
 ->join('users','products.user_id' ,'=' ,'users.id')
 ->whereIn('users.id', $explodedUserIds)
 ->delete();
01 Jul
1 year ago

hondnl started a new conversation Testing View Response As JSON Without Touching The Controller

In the lesson https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/17

A User Can Filter Threads By Popularity

There is a part where we are trying to test if a list of threads is ordered by the amount of replies it got.

Original test :

function a_user_can_filter_threads_by_popularity() { $threadWithTwoReplies = create('App\Thread'); create('App\Reply', ['thread_id' => $threadWithTwoReplies->id], 2);

    $threadWithThreeReplies = create('App\Thread');
    create('App\Reply', ['thread_id' => $threadWithThreeReplies->id], 3);

    $threadWithNoReplies = $this->thread;

    $response = $this->getJson('threads?popular=1')->json();

    $this->assertEquals([3, 2, 0], array_column($response, 'replies_count'));
}

The problem with this is that you have to touch your ThreadsController if you want it to work.

You have to add :

if (request()->wantsJson()) { return $threads; }

I find this very messy , I don't want to touch my original code when testing.

in https://github.com/laracasts/Lets-Build-a-Forum-in-Laravel/blob/master/tests/utilities/functions.php I have added a helper function to remove the problem.

function fakeJsonCall($response,$itemKey, $json = false ){

$content =$response->getOriginalContent()->getData()[$itemKey];

$data = array();
foreach($content as $item){
    $data[]=$item['original'];
}

if( !$json) return $data;

return json_encode($data);

}

and then the test becomes :

public function a_user_can_filter_threads_by_popularity() {

    $threadWithTwoReplies = create('App\Thread');
   create('App\Reply',['thread_id' =>$threadWithTwoReplies->id],2);

    $threadWithThreeReplies = create('App\Thread');
    create('App\Reply',['thread_id' =>$threadWithThreeReplies->id],3);

   $threadWithNoReplies = $this->thread;


   $response =$this->get('/threads?popularity=1');

   $data=fakeJsonCall($response,'threads',false);

   $this->assertEquals([3,2,1], array_column($data,'replies_count'));


}

Now I do not have to touch my controller....

My question is , is there a more elegant way to do this with original Laravel code ?

25 Jun
1 year ago

hondnl left a reply on REST App Deploy On VPS (best Practice)

You might want to consider Nginx as webserver... A lot more stable and faster. If you ever get in trouble with performance ... rather take a look at varnish then upgrading your server.

https://murze.be/2017/01/varnish-on-a-laravel-forge-server/

Good luck

16 Nov
2 years ago

hondnl left a reply on Laracasts Refresh

Hi Jeffrey,

Great design , couple of very nice UI upgrades. One that I do not really get is the "stream" . You mixed series + lessons together and it is less clear. I miss the chronological list if only lessons so you can quickly see what is new. Now you have to figure out what date it really was posted .. sep 20th ? or November 15th... ah no , one is a series the other one a lesson. Could be more clear :)

Eg: Learn Redis Through Examples Series: 7 Episodes TOOLING • SEP 20TH, 2016 • INTERMEDIATE • 01:14:36 ADD TO WATCHLIST

Fetch In Progress Articles Learn Redis Through Examples - Episode #7 TOOLING • NOV 15TH, 2016 • INTERMEDIATE • 10:08 ADD TO WATCHLIST