TheNephilim

TheNephilim

Member Since 3 Years Ago

Experience Points 26,430
Experience
Level
Lessons Completed 324
Lessons
Completed
Best Reply Awards 5
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.

05 Jun
6 months ago

TheNephilim left a reply on Using Policies To Restrict Access To Data From Relations

I'm probably going to limit access in the transformers used by the API. Another way would be to limit access in the toJson method of the model, but in my case the transformers (using https://github.com/spatie/laravel-fractal) is a better way.

01 Jun
6 months ago

TheNephilim started a new conversation Using Policies To Restrict Access To Data From Relations

Lets assume having a Customer model with an orders() and an offers() relationship. Both are eager loaded.

Now using policies I have restricted the Offer model to be only visible to certain roles. How can I prevent the offers bleeding through the Customer model offers() relation?

  1. At the controller level? In my case using load() I have to build an array of relations that the user is allowed to see.

  2. At the relation level? Returning an empty relation or something?

What's the go-to solution for this and how are you guys approaching things like this?

03 May
7 months ago

TheNephilim left a reply on SQLite Migration Failing To Add Deleted_at (soft Delete Column)

How did you fix this? Having the same issue :/

25 Apr
7 months ago

TheNephilim started a new conversation Iterating Over API, Getting Results In Batch

For getting data from an API, I need to add skip and take query parameters for fetching all data.

So in this case I have something like this:

$products = $repository->getProducts(['skip' => 0, 'take' => 10]);

When there are no more records, $products will be an empty array. How can I iterate over the $products = $repository->getProducts(['skip' => 0, 'take' => 10]) method when I don't know how many records to expect?

I was thinking something along the lines of (pseudo code):

while ($products = $repository->getProducts(['skip' => 0, 'take' => 10]) && !empty($products)) {

    // process $products

    $skip = $skip+10;

}

Any suggestions?

02 Feb
10 months ago

TheNephilim started a new conversation Having A PageController Defer To PageTemplate

So, I have a general PageController which will get the page from the database and figure out what template the page uses. The template class get initialized with the page data and the Responsable contract makes sure the toResponse method gets called and it shows the view.

See the example below:

Route::any('{path?}', '[email protected]');
class PagesController extends Controller
{
    public function handle(Page $page)
    {
        if ($page->template)
            return $this->getTemplate($page);

        return view('templates.default', ['page' => $page]);
    }
}
class ContactTemplate extends Template
{
    public function toResponse($request)
    {
        return view('templates.contact', ['page' => $this->page]);
    }
}

This all works fine, but I'm struggling how to handle anything other then GET requests. For instance, the ContactTemplate has a contact form that can be submitted. I'd rather keep that code in the ContactTemplate rather then the PageController.

Anyone here have a nice clean solution?

15 Nov
1 year ago

TheNephilim left a reply on Timestamps Error When ->using('PivotModel')

Having the same issue! Can't update a value in my pivot table.

TheNephilim left a reply on Authenticate A Device Rather Then A User

@SapporoGuy I'd rather have a token for the device, like for authenticating API requests for example.

My use case:

  • Display without keyboard/mouse loads a preset URL in the browser.
  • URL hit's a Laravel app and generates plus displays a code to the user.
  • User can login, on another PC, type the code into a form and select what to display on the screen.
  • The screen will receive a URL to load, via websockets.
  • That URL should be guarded and I'd like to add ?access_token=... to the URL for authenticating.

So, I need a guard for the device that authenticates using an access token.

14 Nov
1 year ago

TheNephilim started a new conversation Authenticate A Device Rather Then A User

Let's assume I have to authenticate a device rather then a user. Can I use a custom guard linked to a devices table and authenticate by using a token or something?

I've been fiddling around a bit, but it doesn't seem to work and I have no idea what's exactly going wrong here. So is it even possible?

09 Nov
1 year ago

TheNephilim started a new conversation Listing (rather Then Nesting) A Parent/child Model Using Recursive Component

Currently I have a component that recursively displays it's children and so on. The problem I'm having is that it will nest the displayed results further and further. I don't want the elements nested, I want them in a list. Somehow I think the solution is in using scopes/slots/templates/etc., but I can't figure it out.

Below how I use the component:

<recursive-item v-for="item in items" v-bind:key="item.id" v-bind:item="item"></recursive-item>

Below the template for the component, containing the recursiveness:

<template>
    <div>
    <div>{{ item.name }}</div>
    <recursive-item v-for="childItem in item.children" v-bind:key="childItem.id" v-bind:item="childItem"></recursive-item>
    </div>
</template>

Now the template>div will keep nesting the children, but I need a root element like a div. While practically I'd like to do this:

<template>
    <div>{{ item.name }}</div>
    <recursive-item v-for="childItem in item.children" v-bind:key="childItem.id" v-bind:item="childItem"></recursive-item>
</template>

Anyone here that has any idea of how to solve something like this.

27 Sep
1 year ago

TheNephilim left a reply on Add Joined Data To JSON Output.

@Parasoul I tried that, with a hasManyThrough relation, but that looses binding with the user, so that does not work for me. Also relation->relation doesn't work because of the way it's all setup.

@sutherland Eloquent API Resources might indeed be a solution to this. Thanks!

I'm still not very happy with the whole thing. As explained in the "story behind al this..." paragraph, putting models/relations/etc. together is a challenge in general :/.

21 Sep
1 year ago

TheNephilim started a new conversation Add Joined Data To JSON Output.

I have a controller that looks like this:

    public function show(Order $order)
    {
        $order->load([
            // some more relations
            'users' => function ($query) {
                // query with addSelect and some joins
            },
        ]);

        return view('orders.show', [
            'order' => $order,
            'users' => User::all(),
        ]);
    }

Now, how can I get the columns that I added with addSelect to be visible in the JSON output of the model? All documented solutions are for appended attributes with a get method in the model definition.

Story behind all this is that I have a an order, to which users can be assigned to. If an order is assigned to a user, the user will see it in it's inbox. When in inbox the user may put the order on a 'to do list' of their choosing. When displaying the order, I want to show all users assigned to the order and show the title of the 'to do list' per user (assignee).

23 Jun
1 year ago

TheNephilim left a reply on Eloquent's MorphedByMany Method

Yup, having the same issue :/

16 Jun
1 year ago

TheNephilim started a new conversation Returning Muliple Models In A Single Collection

I'm working on a user inbox. Not the traditional kind with just messages, but one that shows assigned orders/offers/etc. See (incomplete) code below:

<?php

namespace App;

class User extends Model
{
    protected $appends = ['inbox'];

    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }

    public function offers()
    {
        return $this->belongsToMany(Offer::class);
    }

    public function getInboxAttribute()
    {
        return collect($this->orders)
            ->merge($this->offers)
            ->sortBy(function ($item, $key) {
                return $item->pivot->order_column;
            })
            ->values()
            ->all();
    }
}

So in order to use the inbox in a Vue component, I need to append it to the User. I'm also ordering on a order_column, which is just an integer containing the order position.

Is there a better way to to this? Could a make the inbox a kind of relation, so I can say $currentUser->with('inbox') instead of having to append the inbox. The way I'm doing it now seems kind of expensive.

12 Jun
1 year ago

TheNephilim left a reply on My Web.php Routes Are Broken After Uninstalling A Plugin

Did you remove the ServiceProvider for the package, as well as the routes?

TheNephilim left a reply on Validation Continues After Required_with Fails.

Well the password is not required. It's part of the account page, where you can update e-mailadres and username too. So if no password was entered, we won't update the password for the user.

Therefor current_password should only be required with the password field.

The problem is that it will always run the check_password rule, even when the password field was empty.

@tobiasj @Screenbeetle

09 Jun
1 year ago

TheNephilim started a new conversation Validation Continues After Required_with Fails.

Been staring at this for a bit too long; maybe someone can give me a hint on what I'm missing here.

For a user to change their password, I want them to enter the current password. So I created a custom validation rule like this:

Validator::extend('check_password', function($attribute, $value, $parameters, $validator) {
    return Hash::check($value, auth()->user()->password);
});

In my controller I have the following rules setup:

$this->validate($request, [
    'password' => 'confirmed',
    'current_password' => 'required_with:password|check_password',
]);

But even when password is null, the validation proceeds to the check_password and fails.

23 May
1 year ago

TheNephilim started a new conversation [Promise|axios] Get A New Token When Token Invalid/expired, But Cancel When Getting Token Does Not Work

I'm struggling all afternoon with this... nearly started crying :(

export const http = axios.create();

http.interceptors.response.use((response) => {

    if (response.headers.authorization) {

        let newToken = response.headers.authorization.replace(/^Bearer /i, '');

        ls.set('jwt.token', newToken);
    }

    return response;

}, (error) => {

    if ((error.response.status === 400 || error.response.status === 401) && error.config && !error.config.__isRetryRequest) {

        error.config.__isRetryRequest = true;

        return http.get('/token', null).then((response) => {

            ls.set('jwt.token', response.data.token);

            return http(error.config);

        }).catch((error) => {

            throw error;

        });

    }

    throw error;

});

Currently; fetching a new token and retrying the requestworks fine. But... if it fails to get a new token, it starts retrying infinitely. How can I stop when fetching a new token does not work?

17 May
1 year ago

TheNephilim started a new conversation Fetching Pivot Data From Two Known Models

Lets assume the following;

I have two models that have a ManyToMany relation. The pivot table (post_user) also contains a text/json field named permissions.

class User extends Model {

    public function posts()
    {
        return $this->belongsToMany(Post::class)->withPivot('permissions');
    }

}
class Post extends Model {

    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('permissions');
    }

}

Then I have a Policy to check the rights a user has for a post it was added to. Currently I have to get permissions like this...

class PostPolicy {

    public function update(User $user, Post $post)
    {
        $permissions = $user->posts()->find($post->id)->pivot->permissions;

        return $user->owns($post) || $permissions['update'];
    }

}

So I already have both models, but I still need to fetch pivot separately. Is there a better way to do this?

24 Apr
1 year ago

TheNephilim left a reply on Laravel Passport Api Guard Not Working

Did you go through all the installation steps for Passport?

https://laravel.com/docs/5.3/passport

04 Apr
1 year ago

TheNephilim left a reply on Hosting Godaddy.com Not Support Laravel 5.4

Check out https://www.fortrabbit.com/laravel-hosting which takes care of everything.

Otherwise DigitalOcean with Laravel Forge is a very nice combination.

I like that Laravel Forge just charges $15 per user, instead of per project. But the downside is, that when hosting just one project or starting with one project, it can be a bit costly.

TheNephilim started a new conversation Get Values That Aren't In The GROUP BY

For a query that has some aggregates, I need to get the values from the latest row. LEFT JOIN does not seem to work, but more then one or two subselects are not very optimal either. How can I get those values, that aren't in the GROUP BY?

Currently I get them like this:

SELECT entries.col_a, entries.col_b, SUM(entries.col_c), (SELECT col_d FROM entries as e WHERE e.id=MAX(entries.id)) as col_d from `entries` where entries.`ended_at` is not null group by entries.`col_a`, entries.`col_c`

Like I said; one subselect is not really an issue maybe, but I need more values from more columns and the LEFT JOIN doesn't work.

Any ideas?

31 Mar
1 year ago

TheNephilim started a new conversation Get Rows Where Modulo Is Not 100

I'm not sure how to describe the problem, but I have this data:

| activity | completion | | --------- | ---------- | | a | 25 | | a | 75 | | a | 100 | | b | 100 | | b | 50 |

Then I want to know which activity has not been completed. With this data A has 25+75, then 100 so modulo (?) is 100. But B has 100, but then 50, so this activity is not completed.

With a group by on activity; how can I get the activities with an 'open end'?

I tried something with https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_mod, but that does not give me the right results.

30 Mar
1 year ago

TheNephilim left a reply on Carbon Missing Leading Zero For Minutes

@ohffs That's it indeed, thanks! I did not no there was an alternate format for the interval, but that explains it.

29 Mar
1 year ago

TheNephilim left a reply on Carbon Missing Leading Zero For Minutes

I tried that, but it just returns 'H:i:s'. Which is weird by itself anyway :P

TheNephilim started a new conversation Carbon Missing Leading Zero For Minutes

The following code outputs the time 00:0:00 (note the missing leading zero for minutes).

$entry->started_at->diff($entry->ended_at)->format('%H:%i:%s');

Is there any way to fix this? I can't find anything in the docs or someone with the same issue :(.

17 Mar
1 year ago

TheNephilim started a new conversation Proper Table Layout For Shared Item

When an item is created and owned by a user, but can be shared with other users; what would be the best way to do that?

I was thinking:

posts
- id
- owner_id
- etc.

post_user
- id
- post_id
- user_id

The owner_id on posts to save the owner of the post, and users the post is shared with are stored in the post_user pivot table.

I think storing a record for the owner in post_user too, would be helpful in keeping querying easier.

07 Mar
1 year ago

TheNephilim left a reply on Getting Average Per Type Of Activity

@Connor-S-Parks: That half way; I would get one row per activity and employee. But I need one row per employee, with the activities' average time.

I figured Eloquent would be able to do that, with a bit of magic :+

TheNephilim started a new conversation Getting Average Per Type Of Activity

Been trying to solve this now for a few days, but I can't get my head around it. Assume the following database table structure:

entries
- id
- employee_id
- activity_id
- started_at
- ended_at
employees
- id
- name
activities
- id
- name

Now I would like to create a table that displays the average time per activity. Like this:

<table>
    <thead>
    <tr>
        <th>Employee</th>
        @foreach($activities as $activity)
            <th>{{ $activity->name }}</th>
        @endforeach 
    </tr>
    <thead>
    <tbody>
    @foreach($entries as $entry)
        <td>{{ $entry->employee->name }}</td>
        @foreach($entry->activities as $activity)
            <td>{{ $activity->avg_time_per_activity }}</td>
        @endforeach 
    @endforeach 
    </tbody>
</table>

I tried solving this with regular SQL but I haven't found a solution yet. Besides that; I don't know what to search for :o.

13 Feb
1 year ago

TheNephilim left a reply on Cannot Access Data From Within Component Method

Still no idea actually :o Might have something to do with the syntax of the data object/function. Try:

data() {
        return {
        categories: []
    };
}
01 Feb
1 year ago

TheNephilim started a new conversation Need Values To Exists In Multiple Aggregate Arrays

Having a bit of a pickle here...

Got this kind of records in the database:

Type: id, name. Entry: id, date. entry_type: id, entry_id, type_id, value. (pivot table with value)

There are 3 types and every Entry has a value for those 3 types.

I've managed to get an SUM of value grouped by type and by date. Resulting in the following array:

[
    'type' => 'Type 1',
    'date' => '2017-01-01',
    'amount' => 33, // SUM(value)
]

But... I need an array like this...

[
    'Type 1' => [
        '2017-01-01' => 33,
    ]
]

To create a bar graph that shows the types next to each other.

After bickering around, because I need the Collection groupBy first and then the Eloquent pluck, I got what I need. But... there has to be an easier way :o.

13 Jan
1 year ago

TheNephilim left a reply on Getting Data From Text File And Inserting Into Database.

Indeed; creating a table which checks to see if a file was processed and if the which line number was processed last could be the way to go.

Save a filename field and a linenumber field.

If filename does not exist in the table; start processing at the top of the file and if filename does exist start at linenumber+1 in the file.

I think you can use fseek to start at a given linenumber, instead of fgets: http://php.net/manual/en/function.fseek.php

TheNephilim left a reply on Echo Private Channels Seem To Not Be Broadcasting.

Can you return an array with multiple channels in the broadcastOn function?

And did you authorize the channel: https://laravel.com/docs/5.3/broadcasting#authorizing-channels

TheNephilim left a reply on Updating Changes To Live Server Without Forge

You could use a git remote on the server, so then you can push your changes from SourceTree to the remote server.

Check this out, though it might be a bit outdated: https://www.digitalocean.com/community/tutorials/how-to-set-up-automatic-deployment-with-git-with-a-vps

TheNephilim left a reply on Comma Delimiter For Floats, Whie Using Setlocale(LC_ALL) And PDO

Are you using number_format or money_format in your Blade templates to display a value?

Simply doing $expense->amount should output 12.34. Formatters like number_format take the locale into account (I believe) so you'd get 12,34.

19 Dec
1 year ago

TheNephilim left a reply on Laravel Sending Mail On Localhost Not On Production (MAILGUN)

I'm guessing port 465 is closed by the firewall of the production server. But you should be sending mail through the Mailgun API and not SMTP.

Check out https://laravel.com/docs/5.3/mail#introduction, did you adjust the config in config/services.php?

13 Dec
2 years ago

TheNephilim left a reply on Only Accept Bitcoin?

Mollie accepts Bitcoin payments: https://www.mollie.com/en/bitcoin

There's a code example which shows how easy it is to use the API they provide. Been using this payment provider for nearly 10 years and still a happy user.

08 Dec
2 years ago

TheNephilim left a reply on Getting Data From Text File And Inserting Into Database.

Is there a unique identifier per calll? Otherwise you could check if it already exists in the database.

Another way would be to save the line number of the last line you processed from the file. That way you could resume there if you reload the view.

28 Nov
2 years ago

TheNephilim left a reply on Laravel/Passport - Isn't That Security Hole?

You don't know the secret key the JWT was generated with. Check this out: https://jwt.io/introduction/

01 Nov
2 years ago

TheNephilim started a new conversation [Vue V1.x] Showing A List Of Items, Then Build A New List For Items With Values

Well I have no idea how to describe it, so see the following example: https://jsfiddle.net/c6e7py1j/. It's just a small piece of code to illustrate the problem I have.

Situation: I have an array of categories, with in each category an array of items which I display.

I want to: Fill another array with items that have a value. In my example it would mean that 'Lorem' should be 1 as it exists in the items array. Also when entering a value for one of the other category items, it would be added to the items array with the entered value.

I've tried some approaches but they all end somewhere halfway. So if any of you have a good idea it would be awesome! :D

21 Oct
2 years ago

TheNephilim left a reply on How You Would Refactor This ?

What are you trying to accomplish? Are you already using Vue or do you want to start using it, with this code as an example?

17 Oct
2 years ago
13 Oct
2 years ago

TheNephilim left a reply on L5.2: Wildcard In Domain (route Group)

I did not get this to work in Laravel 5.1 either. I 'solved' it this way:

Route::group([
    'domain'        => '{variable}.'.env('APP_DOMAIN')
], function () {
    //
});

While {variable}.* would be desired in my case.

TheNephilim left a reply on Best Way To Count Nested Relationships

I guess using the reduce function could help here: https://laravel.com/docs/5.3/collections#method-reduce

$postCount = $category->posts->reduce(function ($count, $post) {
    return $count + $post->replies->count();
}, 0);

TheNephilim left a reply on Problem After Composer Update

Delete the vendor folder, then with the original composer.lock file run composer install.

06 Oct
2 years ago

TheNephilim left a reply on Schema Builder Unique()

Check the example below:

/**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        Schema::drop('tablename'); // table with foreign key contraints
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

TheNephilim left a reply on Response()->json Returns Content-type Text/html On Error

Try return $decoded_data; instead of specifically using the json response method.

TheNephilim left a reply on Laravel Used Without Terminal Support

I believe it can be done, but it's definitely not how Laravel should be used. How to in short;

  • Install Laravel on local machine
  • Run composer install
  • Upload whole directory (without node_modules) to the server you want to run Laravel on
  • Make sure /public is the document root.
28 Sep
2 years ago

TheNephilim left a reply on Laravel Routes On Subdomain "Not Found" (Root Route Works) [DigitalOcean]

Can you test if everything is rewritten to index.php correctly?