hondnl

hondnl

Member Since 2 Years Ago

Experience Points 17,160
Experience Level 4

2,840 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 152
Lessons
Completed
Best Reply Awards 2
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

01 Jun
1 month ago

hondnl left a reply on Magento 2: Can I Ask Question About Magento 2.x ?

@SNAPEY - haha I came to the same conclusion. I once had to do a project based on magento. It was the most hellish couple of months in my career. Most of it was to hack yourself around the code and try to optimize the slowness of the framework.

hondnl left a reply on PHP Storm

I agree, would be nice to have an update. Pretty sure I am still not using all the nifty tricks phpstorm has to offer.

30 May
1 month ago

hondnl left a reply on Map Array Values To Collection Of Items

Final edit and solution :

This below will make sure only the values from the basemap are returned and if they are not aligned in order with the items it will still return the right results. And it is all with collections.

$baseMap = collect($baseMap)->sortKeys();

$result = $items->map(function ($item) use ($baseMap) {

            return $baseMap->values()
                ->combine(
                    collect($item)->sortKeys()->intersectByKeys($baseMap)
                )
                ->all();
        });

29 May
1 month ago

hondnl left a reply on Map Array Values To Collection Of Items

Update for the users interested :

Dirty , but collections only , must be a cleaner way to do this!

$baseMap = collect($baseMap);

$results = $items->map(function ($item) use ($baseMap) {

            return collect($item)
                ->only($baseMap->flip())
                ->mapWithKeys(function ($value, $key) use ($baseMap) {


                    return [$baseMap->get($key) => $value];


                })
                ->all();

        })->all();

Or just plain php :


$result = $items->map(function($item) use ($baseMap) {
    $array = [];

    foreach($baseMap as $oldKey => $newKey){
        if(isset($item[$oldKey])){
            $array[$newKey] = $item[$oldKey];
        }
    }

    return $array;
})->all();

hondnl left a reply on Map Array Values To Collection Of Items

Thanks for replying. But baseMap will be dynamic. As a class property for example.

 protected $baseMap =[
        'name' => 'new_name',
        'year' => 'new_year',
        'same' => 'same'
    ];


// In another class for example

public function map(Collection $items,$baseMap){

         
        /// the magic needs to happen here...



}

hondnl started a new conversation Map Array Values To Collection Of Items

How would one do the following elegantly with laravel collections ?

Map the values of the $baseMap as keys to the collection.

The baseMap :

    $baseMap = [
                'name' => 'new_name',
                'year' => 'new_year',
            ];

The collection :

     $items = collect([
                [
                    'name' => 'name1',
                    'year' => '1000',
                    'not_in_basemap' => 'foo'
                ],
                [
                    'name' => 'name2',
                    'year' => '2000',
                    'not_in_basemap' => 'foo'
                ],
                //...
            ]);

The end result :

    $result =[
                [
                    'new_name' => 'name1',
                    'new_year' => '1000',
                 
                ],
                [
                    'new_name'=> 'name2',
                    'new_year' => '2000',
                 
                ],
            ];

I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!

03 May
2 months ago

hondnl left a reply on How To Override Illuminate\Database\Connection Class

Not sure it would be the best path ... Take a look at https://stidges.com/extending-the-connection-class-in-laravel it is an old article , but most will be the same...

Why not just use the database logging in (my/post)sql ? that would give you all the data you need. https://dev.mysql.com/doc/refman/8.0/en/slow-query-log.html

hondnl left a reply on How To Override Illuminate\Database\Connection Class

You could do this instead in your AppServiceProvider without touching any vendor code ( or create a serviceProvider yourself)

in your boot method

     DB::listen(function ($query) {
                  // do anything you want each time the db is called...
        });

And example i use myself to debug the queries.

     DB::listen(function ($query) {
            if(!preg_match('/(information_schema|migrations|drop table|create table|alter table)/i',$query->sql)) {
                echo '<pre>';
                print_r([
                    $query->sql,
                    $query->bindings,
                    $query->time
                ]);
                echo '<pre>';
            }
        });

hondnl left a reply on How To Override Illuminate\Database\Connection Class

What do you want to achieve ?

hondnl left a reply on Shorter Code For Resetting To NULL

A middleware could be made , but since you only want certain fields returning an empty string ( the ones with a text field in the db ) I would make a traid :

trait TrimAndReturnEmpty {


          public function trimIfEmpty($request,$key){

             // put the code you created above. 

          }

}
``


then in a controller or wherever you want to use it.

use TrimAndReturnEmpty; // on top

// in your method.

$message->content = $this->trimIfEmpty($request,'content');


Would clean it up and you could reuse it where needed without creating overhead where you don't.

hondnl left a reply on Eloquent Optimizations

I think it would be efficient in the long run to learn SQL itself. I found that a lot of people use laravel Eloquent completely wrong just because they don't understand what is really happening.

If you want to know what laravel eloquent is actually asking to a database , you could play around with a simple debug feature. ( never do this on production).

Go into your Providers/AppServiceProvider and in the boot method add this :

    DB::listen(function ($query) {
            if(!preg_match('/(information_schema|migrations|drop table|create table|alter table)/i',$query->sql)) {
                echo '<pre>';
                print_r([
                    $query->sql,
                    $query->bindings,
                    $query->time
                ]);
                echo '<pre>';
            }
        });

It will output the raw sql query and also the time it took. You will learn more easily what is happening at the back of laravel.

And as stated above , getting all the records and then looping over them to find the right one is a very wrong approach. Maybe if just one request is asked, since it could be lightly cached , but imagine 1000 concurrent requests asking the same thing. Get it out of your head , in the long run this will be very bad for your application.

If you want to improve a request time on searching on columns, certain indexes might help (http://www.mysqltutorial.org/mysql-index/)

Good luck

29 Apr
2 months ago

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

@MARTINZELTIN - It does not make sense... The only thing values() does is reset the order of the keys in the array. It should not make a difference in the order of the values.

sortBy works for me on both plain array and an array of objects. I still does not make sense you got a different output.

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

This is weird... Alright so you got an array of objects... Not just a plain array.

But even when I try to replicate a part of your array , I get the results we want.

 $activity_time =[
            (object) ['activity_time' =>'2019-04-29 12:28:07'],
            (object) ['activity_time' =>'2019-04-29 12:25:31'],
            (object)  ['activity_time' =>'2019-04-16 17:10:24'],
            (object)   ['activity_time' =>'2019-04-29 12:24:53'],
            (object)   ['activity_time' =>'2019-04-17 12:40:17'],
        ];

        $activity_time =collect($activity_time )->sortByDesc(function($item,$key){


             return strtotime($item->activity_time);
        });

        dd($activity_time);

There might be something going wrong because of the objects... Try to do the following :


 $activity_time=collect($activity_time)->map(function($item){

            return [
                'activity_time' =>$item->activity_time
            ];
        })->sortByDesc(function($item,$key){

            return strtotime($item['activity_time']);
        });

hondnl left a reply on Multiple Relations On An Eloquent Model

Take a look at eager loading relationships https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

Or use the DB builder https://laravel.com/docs/5.8/queries And use joins.

Try them out .. best way of learning :) If you get stuck doing it , we will be here..

hondnl left a reply on Crawling Dynamic Data In Laravel

If I get you right , you send a request on your frontend with javascript to Amazon , receive json data and now are wondering how to store this data in your backend ?

Or you want to crawl data on an external site , but the data is generated dynamically with javascript?

We need some more info here.

hondnl left a reply on Use Lumen And Laravel In Single Project Structure

Take a look at https://github.com/laurencei/laramen

It might be what you are looking for ...

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

@MARTINZELTIN - There must be something wrong in your original array. I am asking about the output of the original array ( before collect) , not the collection.

Look at this example . This works, so there must be something different with the inital input.


$activity_time =[
            ['activity_time' =>'2019-04-29 12:28:07'],
            ['activity_time' =>'2019-04-29 12:25:31'],
            ['activity_time' =>'2019-04-16 17:10:24'],
            ['activity_time' =>'2019-04-29 12:24:53'],
        ];



        $activity_time =collect($activity_time )->sortByDesc(function($item,$key){

             return strtotime($item['activity_time']);
        });

        dd($activity_time);

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

@MARTINZELTIN - What is the original latest_activities ? You sure it is an array?

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

@MARTINZELTIN - Show me the original $latest_activities array...

And strtotime($activities['activity_time']); btw..

hondnl left a reply on Can't Get SortBy To Work With A Timestamp - Getting Wrong Order

Try converting it to an integer... just use strtotime for example.

$latest_activities =collect($latest_activities)->sortByDesc(function($item,$key){ return strtotime($item['activity_time']); });

21 Feb
5 months 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
7 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
9 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
9 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
11 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
1 year 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();
19 Jul
2 years ago
01 Jul
2 years 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
2 years 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