MartinZeltin

MartinZeltin

Member Since 4 Months Ago

Experience Points 10,200
Experience
Level
Lessons Completed 65
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

15 Jan
2 days ago

MartinZeltin left a reply on Is There A Way To Sort A Collectin Using SortBy($key, 'asc/desc')?

@REALRANDYALLEN - But I still need to check if the $order is == 'asc' or 'desc' and do sortBy or sortByDesc instead of passing it as second argument?

MartinZeltin started a new conversation Is There A Way To Sort A Collectin Using SortBy($key, 'asc/desc')?

I noticed that the sortBy methods are a little bit different on Collection than on Query Builder, I'm not sure why that is. It seems more difficult to sort a collection by a key since it does not accept a second argument for asc/desc.

I would love to be able to sort by collection like this but I can't.

    $order = 'desc';
    $sorted = $collection->sortBy($company->user->id, $order)

But instead I have to do it this way. (As far as I know).

    $sorted = $collection ->sortBy(function ($item) {
        return $item->company->user->id;
    })

So... is it possible to sort like with the first (much shorter) method?

And is it possible to specify the order of 'asc/desc' without doing a if/else like this...

    if ($order == 'asc') {
        $sorted = $collection ->sortBy(function ($item) {
            return $item->company->user->id;
        })
    } else if ($order == 'desc') {
        $sorted = $collection ->sortByDesc(function ($item) {
            return $item->company->user->id;
        })
    }

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

Is it also possible not to hard-code $item->work_time but be able to use sumTimes('key_here')?

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

@ADAMPRICKETT - Oh, I see, thanks for the explanation.

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

@S4MUEL - works like a charm! :) Thanks!

Out of curiosity, what does this line mean? Why is it at the very end?

    }, ['h' => 0, 'm' => 0, 's' => 0]); 

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

Now I'm getting Illegal offset error

ErrorException (E_WARNING)
Illegal string offset 'h'

at: $sum['h'] += intval($h);

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

@ADAMPRICKETT - I'm getting an error

$total = $this->database->work_time_stats->sumTimes('work_time');
ErrorException (E_WARNING)
A non-numeric value encountered

at: $sum['h'] += $h;

My macro looks like this:

Collection::macro('sumTimes', function () {
    return $this->reduce(function ($sum, $value) {
        list($h, $m, $s) = explode(':', $value);

        $sum['h'] += $h;
        $sum['m'] += $m;
        $sum['s'] += $s;
        
        $sum['m'] += floor($sum['s'] / 60);
        $sum['h'] += floor($sum['m'] / 60);
        $sum['s'] = $sum['s'] % 60;
        $sum['m'] = $sum['m'] % 60;
        
        $sum = implode(':', $sum);

        return $sum;
    }, ['h'=>0, 'm'=>0, 's'=>0]);
});

The collection looks like this:

[
    {
        "id": 5071,
        "user_id": 30,
        "work_date": "2018-12-03",
        "work_time": "20:43:59"
    },
    {
        "id": 5072,
        "user_id": 30,
        "work_date": "2018-12-03",
        "work_time": "07:43:59"
    },
    {
        "id": 5073,
        "user_id": 30,
        "work_date": "2018-12-03",
        "work_time": "18:43:59"
    },
]

MartinZeltin left a reply on How Could I Extend Collection With Macros To Sum Times?

namespace App\Providers;

use Auth;
use stdClass;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Collection;

I'm also getting this error

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'Illuminate\Support\Facades\Collection' not found

MartinZeltin started a new conversation How Could I Extend Collection With Macros To Sum Times?

I looked into the sum() function of Collection class and it looks like it only does array_sum($this->items). But if my items contain times in the format of '127:55:12' then it throws an error that it is not an integer. So I wrote a function to sum times and I would like to be able to extend Collection and add sumTimes() function to it. The problem is that I'm not sure exactly how to do it. I suppose I need to map over the collection somehow?

In the end I would love to be able to simply do this to get the sum:

    $total->work_time = $this->collection->work_time_stats->sumTimes('work_time');
    // result: 234:37:12

I have placed this macro in my AppServiceProvider's boot method.

Collection::macro('sumTimes', function () {
    return $this->map(function ($value) {
        //
    });
});

and my function for getting the sum of times looks like this:

$times = [ '217:43:59', '07:50:54', '07:51:43' ];
$sum = [ 'h'=>0,'m'=>0,'s'=>0 ];
    
foreach( $times as $time ) {
    list($h, $m, $s) = explode(':', $time);
    $sum['h'] += $h;
    $sum['m'] += $m;
    $sum['s'] += $s;
}

$sum['m'] += floor($sum['s'] / 60);
$sum['h'] += floor($sum['m'] / 60);
$sum['s'] = $sum['s'] % 60;
$sum['m'] = $sum['m'] % 60;

echo implode(':', $sum); // prints 234:37:12
14 Jan
3 days ago

MartinZeltin left a reply on Can't Use WhereBetween On A Collection (method Not Found)

@PATRICKSJ - I'm on 5.6 I think that was the problem.

MartinZeltin left a reply on Can't Use WhereBetween On A Collection (method Not Found)

@SHEZ1983 - I am trying to gather all the data at first and then work with the collection.

For example I got $this->database->comments->all(); and then worked with that collection. But whereBetween is not working... :(

MartinZeltin started a new conversation Can't Use WhereBetween On A Collection (method Not Found)

I can't seem to be able to use whereBetween method on a collection. It works on an Eloquent model but if it is a local collection then it says not found. Is there a way to perform a whereBetween search on a collection?

Method Illuminate\Database\Eloquent\Collection::whereBetween does not exist.
$comments = $this->database->comments->where('user_id', $user_id)
                                     ->whereBetween('date_from', [$date_from, $date_to])
                                     ->whereBetween('date_to', [$date_from, $date_to])
                                     ->first();

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

@ZION - oh, that's a good point. They are all related by user_id so I could do a where on the date to filter them. I will give it a try.

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

@VILFAGO - Because in one table are comments for that user and time period, then activities, logs, achievements etc. they can't all be in one table. So they are split between multiple tables.

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

@ZION - Simply so that I could avoid making a lot of collections and have just one collection to work with later...

So instead of doing this...

$data->table_one = TableOne::whereIn('user_id', $user_id)
                    ->whereBetween('date_from', [$date_from, $date_to])
                    ->whereBetween('date_to', [$date_from, $date_to])
                    ->get();

$data->table_two = TableTwo::whereIn('user_id', $user_id)
                           ->whereBetween('date_from', [$date_from, $date_to])
                           ->whereBetween('date_to', [$date_from, $date_to])
                           ->get();

$data->table_three = TableThree::whereIn('user_id', $user_id)
                                ->whereBetween('date_from', [$date_from, $date_to])
                                ->whereBetween('date_to', [$date_from, $date_to])
                                ->get();

$data->table_four = TableFour::whereIn('user_id', $user_id)
                              ->whereBetween('date_from', [$date_from, $date_to])
                              ->whereBetween('date_to', [$date_from, $date_to])
                              ->get();

$data->table_five = TableFive::whereIn('user_id', $user_id)
                            ->whereBetween('date_from', [$date_from, $date_to])
                            ->whereBetween('date_to', [$date_from, $date_to])
                            ->get();

I could do simply this...

$data = TableOne::whereIn('user_id', $user_id)
                ->whereBetween('date_from', [$date_from, $date_to])
                ->whereBetween('date_to', [$date_from, $date_to])
                ->with('table_two')
                ->with('table_three')
                ->with('table_four')
                ->with('table_five')
                ->get();

And I would end up with this

[  
   {  
      "id":1,
      "user_id":75,
      "date_from":"2019-01-01",
      "date_to":"2019-01-31",
      "table_two": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
      "table_three": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
   },
   
   {  
      "id":1,
      "user_id":75,
      "date_from":"2019-01-01",
      "date_to":"2019-01-31",
      "table_two": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
      "table_three": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
   },
]

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

@VILFAGO - Yea, that's the thing, it is an array of users, so for each user there should be a key for 'table_two' with an array of that table's data. I may end up just using a bunch of collections (one for each table) instead of trying to join them all together in one collection... meh...

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

Maybe there is a way to use with() without a relationship? Like passing a variable

$table_two = TableTwo::all();

$table_one = TableOne::with('table_two', $table_two);

I tried this but it was asking for a relationship instead of a collection :(

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

Joins also require a foreign key. I thought I could get table_two later and push it into the original collection but it did not work like with(), it just added it at the end.

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

How could I use a join() without overriding column names to end up with a structure like this?

[  
   {  
      "id":1,
      "user_id":75,
      "date_from":"2019-01-01",
      "date_to":"2019-01-31",
      "likes":"5987",
      "table_two": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
        {
            "id":2,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"juice",
        },
        {
            "id":3,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
   },
]

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

These two table are not related by a foreign/local keys but by date_from and date_to columns

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

public function table_two()
{
            return $this->hasMany('App\Models\TableTwo');
}

but it says

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'table_two.table_id

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

This is what my code looks like

$data = TableOne::whereIn('user_id', $user_id)
                    ->where('date_from', $date_from)
                    ->where('date_to', $date_to)
                    ->with(['table_two' => function ($query) {
                        $query->where('date_from', $date_from, $date_to);
                    }])
                    ->get();

MartinZeltin left a reply on Is It Possible To Join Another Table Based On 2 Columns Using With()?

@ZION - I'm getting this error

Illuminate \ Database \ Eloquent \ RelationNotFoundException
Call to undefined relationship [table_2] on model 

MartinZeltin started a new conversation Is It Possible To Join Another Table Based On 2 Columns Using With()?

I have 2 tables that I would like to join using with() based on 2 columns - date_from and date_to; So basically add everything from table 2 where date_to and date_from match from table 1. How could I set up such a relationship?

table 1

id user_id   date_from     date_to    likes
 1   75     2019-01-01   2019-01-31    5987


**table_2**
 id  user_id   date_from     date_to     reward
 1     75      2019-01-01   2019-01-31   'candy'
 2     75      2019-01-01   2019-01-31   'juice'
 3     75      2019-01-01   2019-01-31   'candy'

So that the end result would look like this

[  
   {  
      "id":1,
      "user_id":75,
      "date_from":"2019-01-01",
      "date_to":"2019-01-31",
      "likes":"5987",
      "table_two": [
        {
            "id":1,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
        {
            "id":2,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"juice",
        },
        {
            "id":3,
            "user_id":75,
            "date_from":"2019-01-01",
            "date_to":"2019-01-31",
            "reward":"candy",
        },
      ]
   },
]
12 Jan
5 days ago

MartinZeltin started a new conversation Show @click="" Only If IsAdmin() Is True Without Repeating Myself. Getting Syntax Error.

I have checkbox that when clicked calls a js function but it should only do it if the person logged in is admin. I have @admin directive and also isAdmin() helper function to determine if the person is an admin. But how could I write this without having to repeat myself twice for input field?

@admin
   <input @click="save({{ $_GET["user_id"] }}, '{{ $_GET["date_from"] }}', '{{ $_GET["date_to"] }}')" type="checkbox" class="my-class green">
@else
   <input type="checkbox" class="my-class green">
@endadmin

I would like to be able to do something like this. But I end up with a syntax error.

<input {{ ( isAdmin() ) ? '@click="save({{ $_GET["user_id"] }}, '{{ $_GET["date_from"] }}', '{{ $_GET["date_to"] }}')" : '' }} type="checkbox" class="my-class green">
syntax error, unexpected '?' (View: /var/www/php7/resources/Views/index.blade.php)

<input <?php echo e(( isAdmin() ) ? '@click="save({{ $_GET["user_id"]); ?>, '<?php echo e($_GET["date_from"]); ?>', '<?php echo e($_GET["date_to"]); ?>')" : '' }} type="checkbox" class="my-class green">
11 Jan
6 days ago

MartinZeltin left a reply on Where To Put Javascript?

@ARTISTICRE - Just put your script in your layout head section, it will work.

<html>
<head>
.....

<script type="text/javascript">
   $(window).on('scroll', function() {
    if($(window).scrollTop()) {
     $('nav').addClass('black');
    }
    else {
     $('nav').removeClass('black');
    }
   })
  </script>

...
</head>

MartinZeltin started a new conversation How To Sort A Collection Based On A Key Several Levels Deep?

I have this collection that I would like to sort by $article->tag->id Right now the first item has article tag id of 7 and the second item has 3 and last has 1 but could I sort the collection items so that the first item would be where the article tag id = 1 then where tag = 3 and last where it is 7?

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [article] => stdClass Object
                        (
                            [id] => 1
                            [tag] => stdClass Object
                                (
                                    [id] => 7
                                )
                        )
                )

            [1] => stdClass Object
                (
                    [article] => stdClass Object
                        (
                            [id] => 2
                            [tag] => stdClass Object
                                (
                                    [id] => 3
                                )
                        )
                )

            [2] => stdClass Object
                (
                    [article] => stdClass Object
                        (
                            [id] => 3
                            [tag] => stdClass Object
                                (
                                    [id] => 1
                                )
                        )
                )
        )
)

MartinZeltin left a reply on How Could I Turn This Array Into A Collection To Be Able To Use Collection Functions?

@REALRANDYALLEN - Perfect! That's what I was looking for! It's amazing what you can do with collections :) Thanks!

MartinZeltin left a reply on How Could I Turn This Array Into A Collection To Be Able To Use Collection Functions?

How could I return the items where extra_information->companies->Microsoft->salary > 500 ? I can't seem to go that deep with the where->() function.

MartinZeltin started a new conversation How Could I Turn This Array Into A Collection To Be Able To Use Collection Functions?

I have an array that contains objects that contains arrays - several levels deep. I would like to turn this array into a collection to be able to filter and sort it by user->id, status, etc.

I know I can create a collection like $collection = collect($array);

But how could I use orderBy, filter, where on my new collection?

For example

  1. Return the items where sallary at Microsoft is > 5000 (extra_information->companies->Microsoft->salary)

  2. Sort the collection by status

is this possible?

Here is my original array and created collection.

Original array

Array
(
    [0] => stdClass Object
        (
            [user] => stdClass Object
                (
                    [id] => 7
                    [username] => johnny.ivy
                    [fullname] => Johnny Ivy
                    [phone] => +155599959890
                    [email] => [email protected]
                )

            [today] => 2019-01-11
            [status] => single
            [siblings] => stdClass Object
                (
                    [total] => 2
                )
            [extra_information] => stdClass Object
                (
                    [companies] => Array
                        (
                            [Microsoft] => Array
                                (
                                    [salary] => 500000
                                    [hire_date] => 1990-01-01
                                )

                            [Apple] => Array
                                (
                                    [salary] => 0
                                    [hire_date] => 1978-02-15
                                )
                        )

                )
        )

    [1] => stdClass Object
        (
            .....
        )

)

collect($array)

Illuminate\Support\Collection Object
(
    [items:protected] => Array
     (
    [0] => stdClass Object
        (
            [user] => stdClass Object
                (
                    [id] => 7
                    [username] => johnny.ivy
                    [fullname] => Johnny Ivy
                    [phone] => +155599959890
                    [email] => [email protected]
                )

            [today] => 2019-01-11
            [status] => single
            [siblings] => stdClass Object
                (
                    [total] => 2
                )
            [extra_information] => stdClass Object
                (
                    [companies] => Array
                        (
                            [Microsoft] => Array
                                (
                                    [salary] => 500000
                                    [hire_date] => 1990-01-01
                                )

                            [Apple] => Array
                                (
                                    [salary] => 0
                                    [hire_date] => 1978-02-15
                                )
                        )

                )
        )

    [1] => stdClass Object
        (
            .....
        )
    )
)
10 Jan
1 week ago

MartinZeltin started a new conversation What Does 'as Aggregate' Mean When Performing Sum()?

I noticed that Eloquent adds "as aggregate" when I perform a select sum(column) of something. But what is the difference between just simply selecting sum with "select sum(column) as sum from table" vs "select sum(column) as aggregate from table"?

It seems to return the same result for both ways.

09 Jan
1 week ago

MartinZeltin left a reply on Why Is Sum Of 0.29 Returned Like This - 0.28999999165534973?

@VILFAGO - Well the sum of 0.29 is obviously 0.29, how could I get it to show properly?

MartinZeltin started a new conversation Why Is Sum Of 0.29 Returned Like This - 0.28999999165534973?

When I do a simple database query from phpMyAdmin I get this result

bonuses table

id  bonus_sum
1     0.29

select sum(bonus_sum) as sum from bonuses where id = 1

result:
0.29

But when I do it with Eloquent I get this strange format.

$total = Bonuses::selectRaw("sum(bonus_sum) as sum")
                            ->where('id', 1)
                            ->first()
                            ->sum;

result:
0.28999999165534973?

What is happening here?

03 Jan
2 weeks ago

MartinZeltin started a new conversation How To Properly Check If Collection Is Empty. Always Says It Is Not Empty.

I am trying different ways to check if there are entries that match my select query criteria but there are none. And so it returns NULL. But When I try to verify if it is empty it always says it is not empty.

$total = WorkTimeStatistic::selectRaw("sum(work_time) as work_time, sum(break_time) as break_time, 
               sum(meeting_time) as meeting_time")
  ->where('employeer', $employee_id)
  ->whereBetween('work_date', [$date_from, $date_to])
  ->first();

msg($total);
            
if (!is_null($total)) {
    msg('not empty');
}

if (!empty($total)) {
    msg('not empty');
}

if ($total) {
    msg('not empty');
}

the result I get every time is this

[2019-01-03 11:14:30] local.INFO: array (
   'work_time' => NULL,
   'break_time' => NULL,
   'meeting_time' => NULL,
)

[2019-01-03 11:14:30] local.INFO: not empty
[2019-01-03 11:14:30] local.INFO: not empty
[2019-01-03 11:14:30] local.INFO: not empty
31 Dec
2 weeks ago

MartinZeltin left a reply on Is There A Better/shorter Way To Create Column Filters?

@SNAPEY - Thanks I did not know about scopes so I had to read up on them, looks like there's no other way to make it shorter/cleaner.

MartinZeltin started a new conversation Is There A Better/shorter Way To Create Column Filters?

I have a table that I want the user to be able to filter by columns. So there are input fields above every column where the user can enter a value. However when I put it all together my code started to look kind of ugly and long because I need to check for every value if it exists. Is there a cleaner way to do this?

The code gets very repetitive.

My controller

$data->people = new People();

if (isset($_GET['id'])) {
    $data->people = $data->people->where('id', $_GET['id']);
}

if (isset($_GET['first_name'])) {
    $data->people = $data->people->where('first_name', $_GET['first_name']);
}

if (isset($_GET['last_name'])) {
    $data->people = $data->people->where('last_name', $_GET['last_name']);
}

if (isset($_GET['phone_number'])) {
    $data->people = $data->people->where('phone_number', $_GET['phone_number']);
}

if (isset($_GET['e_mail'])) {
    $data->people = $data->people->where('e_mail', $_GET['e_mail']);
}

if (isset($_GET['address'])) {
    $data->people = $data->people->where('address', $_GET['address']);
}

if (isset($_GET['theme'])) {
    $data->people = $data->people->where('theme', $_GET['theme']);
}

if (isset($_GET['notes'])) {
    $data->people = $data->people->where('notes', $_GET['notes']);
}

if (isset($_GET['favorite_color'])) {
    $data->people = $data->people->where('favorite_color', $_GET['favorite_color']);
}

.........

$data->people = $data->people->orderBy($_GET['sort_by'], $_GET['sort_order'])->paginate(10);
28 Dec
2 weeks ago

MartinZeltin started a new conversation Property [employee] Does Not Exist On This Collection Instance.

Hey guys, I have been banging my head against the wall trying to figure this out. I am trying to create an Eloquent relationship between two tables with no luck. I keep getting this error. Forgive me for the terrible table and column names.

Exception
Property [employee] does not exist on this collection instance.

base_users table

id   user     password            role
 1  Martin 53cc9848ddafdfadf  administrator

base_inkasso table

id   full_name     employer 
 1   John Doe         1

BaseInkasso Model

class BaseInkasso extends Model
{
    protected $table = 'base_inkasso';
    .....

    public function employee()
    {
        return $this->belongsTo('App\Models\BaseUsers', 'employer');
    }
}

index controller

class IndexController extends Controller
{   
    public function index()
    {
        $data = new \stdClass();
        $data->inkasso = BaseInkasso::all();

        print_r($data->inkasso->employee); exit();
    }
}

It always gives me the error that employee property is not found. It should return the results for base_users with id 1 (since employer = 1 in base_inkasso)

12 Dec
1 month ago

MartinZeltin left a reply on Case Insensitive Select?

@GLOBALS - I guess I could. But I still think there is room for improvement to make it even cleaner.

MartinZeltin started a new conversation Case Insensitive Select?

I was wondering if there is a better, more "elequent" way of performing a case-insensitive select than this?

$user = Users::whereRaw("LOWER(username) = '" . strtolower($request->username) . "'")

That looks kind of ugly, if you ask me.

Is there some like like this?

$user = Users::whereCI('username', $request->username)

Behind the scenes this would turn both the column value and the submitted value to lowercase and then do a comparison. Would look a lot cleaner in my opinion.

11 Dec
1 month ago

MartinZeltin started a new conversation How To Create A Class That Will Return An Array Or Single Item?

I am writing a class that I would like to be able to call later and have it return an array of values but it is returning only one.

I would like to be able to use my class like this. If I specify one user id new Blog([10]) then it shouldn't return an array but only one instance. If I specify more than one user id then it should return an array of items.

I am trying to create something similar to how Laravel works where you can say $posts = Posts::all(); or $posts = Post::where('id', 10)->first(); and in the first one it would return an array of all posts and in second it would return only one.

Example usage:

    // Get one user's blog
    $blog = new Blog([10]); // specify user ids
    
    echo $blog->user->name;      // Jane Smith
    echo $blog->posts->title;    // How to draw
    echo $blog->posts->body;     // In this post, I will teach you...
    echo $blog->posts->created;  // 2018-12-01
    echo $blog->theme;           // light/dark/other
    echo $blog->is_awesome;      // no
    
    // Get blogs for users - 10, 20, 30
    $blogs = new Blog([10, 20, 30]); // specify user ids
    
    foreach ($blogs as $blog) {
        echo $blog->user->name;     // John Doe
        echo $blog->posts->title;   // 10 ways to live
        echo $blog->posts->body;    // Hello, in this post I will..
        echo $blog->posts->created; // 2018-12-31
        echo $blog->theme;          // light/dark/other
        echo $blog->is_awesome;     // yes
    }

My class

    Class Blog
    {
        public $users;
        public $posts;
        public $comments;
        public $theme;
        public $is_awesome;
    
        function __construct($users)
        {
            $this->users     = new stdClass();
            $this->users->id = $users; // array of ids
    
            foreach ($this->users as $user) {
                $this->user->name = self::getUsername($user->id)  // John
                $this->posts      = self::getPosts($user->id);    // array of posts
                $this->comments   = self::getComments($user->id); // array of comments
                $this->theme      = self::getTheme($user->id);    // light/dark/other
    
                if ($this->theme == 'dark') {
                    $this->is_awesome = 'yes';
                } else {
                    $this->is_awesome = 'no';
                }
            }
        }
    }
10 Dec
1 month ago

MartinZeltin started a new conversation Vue.js - How Would I Make This In Vue.js Instead Of JQuery?

I am coming from having used jQuery for a long time and now I am trying to switch to Vue.js. I have a list of posts that I am fetching from a database table and I need to perform some actions when I click on each of the posts. I do not know how many posts there will be, it could be 1000 or 10,000 posts. It seemed easy to do it with jQuery but how would I do this with Vue.js?

When a post is clicked

  1. The clicked element's background color changes to red
  2. The element inside with a class "bell-icon" gets added "shaking" class
  3. Lastly, I show a bell modal that has the id of "#bell-modal"

Here is how I made it with jQuery.

PHP / HTML

$rows = Posts::all();

@foreach($rows as $row)
    <div class="row">

        {{ $row->name }}
        <span class="ring-bell">
            <i class="material-icons bell-icon bell-id-{{ $row->id }}">ring_bell</i>
        </span>

    </div>
@endforeach

Javascript

$( ".ring-bell" ).click(function() {
    var bell_id = $( this ).data("bell-id");

    $( this ).css( "background-color", "blue" );
    $(".bell-id-" + bell_id).addClass("shaking");
    $("#bell-modal").show();
});
08 Dec
1 month ago

MartinZeltin started a new conversation Vue.js - Props Don't Update When Input Changes

I have this simple component where I try to bind props both ways but it only works one way. When I change the text in my input fields, it shows 'Initial property 1' to be the value of myprop1 although I changed the input. What could be wrong?

My component

Vue.component('simple-input', {

    template: `
        <div>
            <input type="text" :myprop1="myprop1" :value="myprop1" @input="$emit('input', $event.target.value)">
            <input type="text" :myprop2="myprop2" :value="myprop2" @input="$emit('input', $event.target.value)">
        </div>
    `,

    props: ['myprop1', 'myprop2']

});

main.js

new Vue({
    el: '#root',

    data: {
        myprop1: 'Initial property 1',
        myprop2: 'Initial property 2',
    },

    methods: {
        showMe()
        {
            alert('prop1 - ' + this.myprop1);
            alert('prop2 - ' + this.myprop2);
            
            this.myprop1 = 'new value';
            this.myprop2 = 'new value';
        }
    }
});

HTML

<simple-input :myprop1="myprop1" :myprop2="myprop2"></simple-input>

<button @click="showMe">Show me!</button>

MartinZeltin left a reply on Vue.js - How To Have Multiple Inputs In A Component

@NEILHERBERTUK - Sorry, I am a complete beginner, could you give an example. I have been looking all day at the documentation..

MartinZeltin started a new conversation How To Have Multiple Inputs In A Component

I have just started learning Vue.js and I am trying to get the values from my components. Is there a way to have multiple input fields in my component and get the value of each outside of the component?

For example, if I wanted to get and change the value for both of my input fields in my simple-input component. Right now they both have the same value but I would like to have 2 different values in each input.

My component

Vue.component('simple-input', {

    template: `
        <div>
            <input type="text" :value="value" @input="$emit('input', $event.target.value)">
            <input type="text" :value="value" @input="$emit('input', $event.target.value)">
        </div>
    `,

    props: ['value']

});

main.js

new Vue({
    el: '#root',

    data: {
        value1: 'Initial value 1',
        value2: 'Initial value 2',
        value3: 'Initial value 3'
    },

    methods: {
        alertSimpleInput1() {
            alert(this.value1);
            this.value1 = 'new';
        }
    }
});

HTML

<simple-input v-model="value1"></simple-input>
<simple-input v-model="value2"></simple-input>
<simple-input v-model="value3"></simple-input>

<button @click="alertSimpleInput1">Show first input</button>
06 Dec
1 month ago

MartinZeltin left a reply on The Response Content Must Be A String Or Object Implementing __toString(), "object" Given."

Found the answer, I needed to use this

return response()->json($work_time_statistic);