t0ne

t0ne

Groningen

Member Since 3 Years Ago

Experience Points 10,745
Experience
Level
Lessons Completed 132
Lessons
Completed
Best Reply Awards 1
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.

18 Sep
1 month ago

t0ne left a reply on Need Advice About Model Relations

@martinbean thanks a lot, exactly what I need!

17 Sep
1 month ago

t0ne started a new conversation Need Advice About Model Relations

I need some about the following setup:

a 'User' can work for many 'Department'

For each 'Department' a 'User' has a 'Profile'

user hasMany department (manyToMany) user hasMany profile (oneToMany)

profile belongsTo 1 department AND belongsTo 1 user

department hasMany user (manyToMany) department hasMany profile (manyToMany)

so i could solve it like this:

table structure:

users

  • id

departments

  • id

user_department

  • department_id
  • user_id

profiles

  • id
  • user_id
  • department_id

Is there a better way to solve this? i feels like 'Department' should be polymorph: it can be used for 'users' and 'profiles'.

so instead of:

profiles

  • id
  • user_id
  • department_id

should i use something like this:

profiles

  • id

user_profile

  • user_id
  • department_id
  • profile_id

OR

departmentable (?) (polymorph)

  • department_id
  • departmentable_id
  • type (morph User / Department / Future Model )
20 Sep
1 year ago

t0ne left a reply on Need Some Advice On What's Best Solution To Implement Import Class For All Models

@Parasoul thanks for your reply! Yes all tasks methods apply for all models

@martinbean i want to import data from an excel file to a database table, for example:

  • import 'companies' from excel to the 'companies' table
  • import 'employees' from excel to the 'employees' table
  • import 'whatever' from excel to the 'whatever' table

I want to 'extend/provide' future models with this Import functionality. so i want to get acces to my model from the Import class

For example the analyze method from Import class:


//returns json
//{
//  newRecords:{
//      amount, etc
//  },
//  updatedRecords:{},
//  deletedRecords:{}
//}
//compare excelDataCollection with modelCollection
function analyze(){
    
    $modelCollection = $this->model->all(); //!!?   
    
    $comparison =  new CompareSourceDataWithTargetData($excelCollection,'$modelCollection');    
    //  
    return $comparison->result();
}

'CompanyModelController','CompanyModelController', or 'WhateverModelController'

    function analyzeImportFile(){
        $this->import->analyze();
    }

hope this makes sense;)

19 Sep
1 year ago

t0ne started a new conversation Need Some Advice On What's Best Solution To Implement Import Class For All Models

I want to create a Import class which provides functionality which i can use in all of my controllers.

I came up with some ideas, but I haven't figured it out yet. I might overcomplicate things and looking for the best solution

Option 1.

Import class

class Import{
    
    __construct(Model $model){
        //created in ModelController’s constructor:
        $this->model = $model; 
    }
    
    //get table name used by model
    
    //GOAL: access to model 
    function getTableName(){
        return $this->model->table; //or any other property
    }

    //tasks methods
    function validateRequest(){}
    
    function analyze(){}
    
    function synchronize(){}    

    function getSummary()

}

ModelController: (could be any controller)

use Import;

class ModelController extends Controller {
    __construct(){
        $this->import = new Import(Model $model); //'need model in import class!' use repository?
    }
    
    //GOAL: access to import object
    function analyzeImportFile(){
        $this->import->analyze();
    }
}

Option 2.

abstract Import class

abstract class Import extends Model{
    protected $table;

    __construct(){
        
    }

    abstract function getTableNameValue();  //contract 
    abstract function getPropertyValue();       //contract 

    //GOAL: access to model 
    function getTableName(){
        return $this->getModelTableName()   // exists in child class by contract;
    }

    //import tasks methods
    function analyzeImportFile(){}
}

Model

SomeModel extends Import{
    protected $table = ‘some_table_name’;
    
    private $property = ‘value’;
    
    //don’t want to put stuff in model..    
    //by contract…
    function getTableNameValue(){
        return $this->table;
    }
    
    function getPropertyValue(){
        return $this->property
    }
}

Controller

class ModelController extends Controller {
    __construct(){

    }
    
    //GOAL: access to import object
    function analyzeImportFile(SomeModel $someModel){
        $someModel->analyzeImportFile();
    }
}

Option 3.

The right way..

Option 2 seems not right, Option 1 works fine, but it seems it could be better (should i refactor to repository pattern?)

Or should i take another approach?

i would really appreciate your advice and hope someone can point me in the right direction.

thanks in advance!

25 Aug
1 year ago

t0ne left a reply on Just Launched My Spark App: ZoneWatcher

Thanks your reply, so spark is sufficient for this type of app?

t0ne left a reply on Just Launched My Spark App: ZoneWatcher

Hi @tomschlick,

Saw your laraconus 2017 speech, very helpful!

I hope you will help me understand the following; How does your spark app relates to multi-tenancy? Spark teams can not be used as tenants, am i right?

Thanks in advance!

08 Mar
1 year ago

t0ne left a reply on Laravel-mix With Modules Or Packages

I would also like to know...

23 Jun
2 years ago

t0ne started a new conversation Valet Returns 404 On Tinymce.gzip.php

Valet returns 404 on tinymce.gzip.php, the file is there but i guess it won't accept "gzip.php". Need some advice, thanks in advance!

04 Jun
2 years ago

t0ne started a new conversation Multiple Project Share Same Files. (git?)

I've made a project, which includes a cms and client specific website. Now i want to create another project for another client: (the same) cms + client specific website. What is the best way to keep the cms code in sync, so that all my projects use the same version of the cms.

Should i use git for this? if so, what is the best setup.

hope it makes sense

02 Jun
2 years ago

t0ne left a reply on What Is The Purpose Of Intervention ImageCache?

Thanks for reply!

Example: when i upload an image from my cms i also create a thumbnail and use to create a list of images. /images/thumbnail/image.jpg

Or is better to just upload an image and when want to create a list of images, use imagecache, for example /imagecache/small/image.jpg

t0ne left a reply on What Is The Purpose Of Intervention ImageCache?

Well.. I can see how to use it but i don't understand when to use it.

Can i upload an original image and use imagecache in my website to receive to right format or should i create and store different formats/sizes in the backend and call these images in my website.

t0ne started a new conversation What Is The Purpose Of Intervention ImageCache?

What is the purpose of Intervention ImageCache? Why and when should i use it? When i upload an image i create and store multiple images with their own size, like small, medium, large and use them in my views. thanks in advance!

09 May
2 years ago

t0ne left a reply on Pattern For Media Library

ah oke, it's mess indeed.

Just to be sure: every mediable type has it's own controller for updating and storing etc.

And if i really wanted to: in the MediaController i can make method which returns "one big list of media objects" only for this reason i have make use of polymorphic relation?

t0ne left a reply on Pattern For Media Library

thanks again! why all this? good question, i try all this to learn about polymorphic... maybe not the best use case.

In this case i have my MediaController with an update() method which contains: "$media->mediable()->update($request->all());"

When update my Video or Image or File object, i can sent this request in all of these cases to MediaController->update().

This won't work inserting a Video,Image or File object, in this case need something like Video->media()->store().

And so i ask myself why am i doing all this. I already have it up and running with regular relations.

That's why this post is called "best pattern for media library", is polymorphic the right solution for this case?

06 May
2 years ago

t0ne left a reply on Pattern For Media Library

When trying to update mediable types, i found one of the benefits of polymorphic relations i guess, Am i right?

class MediaController extends Controller{
    
    //one method which can update all the mediable types,
    public function update(Request $request, $id){
        $media = Media::find($id);
        $media->update($request->all());
        
        //updates mediable types (Image, Video etc)
        $media->mediable()->update($request->all());    //!!!!  
    }

}

t0ne left a reply on Pattern For Media Library

@pmall thanks for your reply, now i know on the right track.

Another question: Instead of creating list of all mediable types as above, i need a list of a specific type: how should i do this? This is what i have so far:

get all Videos: option 1

//controller
    //polymorph relation
    $videoList = Video::with(['media'])->get();

    foreach ($videoList as $video) {
        //don't like this:
        dc($video->media);
    }

or

option 2

//model
class Media extends Model{

    public function video()
    {
        return $this->belongsTo('App\Video', 'mediable_id');
    }

}

//controller:
    //belongsTo relation
    $mediaVideoList = Media::with(['video'])->get();
    
    foreach ($mediaVideoList as $media) {
        //makes more sense to me:
        dc($media->video);
    }

t0ne left a reply on Pattern For Media Library

@jekinney Thanks for your advice, i tried this before but it didn't make much sense at the time. I try it again. Media can morph into Image object, File Object, Video Object.

This is what i have so far: (thanks to @martinbean and @pmall)

class Media extends Model
{
    protected $fillable = [
        'title',
        'description',
        'path',
        'thumbnail_path',
        'etc...'
    ];
    
    public function mediable(){
        return $this->morphTo('mediable');
    }
}

class Image extends Model
{
    protected $fillable = [
        'height',
        'width',
        'orientation',
        'alt',
        'ratio'
    ];

    public function media()
    {
        return $this->morphOne('App\Media', 'mediable');
    }
}   

class File extends Model
{
    protected $fillable = [
        'orientation',
        'application',
        'etc..'
    ];

    public function media()
    {
        return $this->morphOne('App\Media', 'mediable');
    }
}

Now i can retrieve a collection with Media Objects which have a 'mediable' relationship which contain a 'Image' or 'Video' or 'File' Object.

So far so good (?)

First question:

$media->mediable morphs into Image,File or Video,
how to determine which object $media->mediable is?
Now i use switch statement, is this the right way to use this pattern?
    //get a mediaList with all Images, Videos and Files 
    $mediaList = Media::with('mediable')->get();
    foreach ($mediaList as $media){
            dc($media->mediable);
            
            //get media thumbnail
            //all mediable object share 'thumbnail' property (Media->thumbnail_path)
            dc($media->thumbnail_path);
            
            //display specific mediable object properties
            //example: 
            //  - 'Video' has 'length' property
            //  - 'Image' has 'ratio' property
            switch (class_basename($medium->mediable_type)) {
                case 'Image':
                    dc($media->mediable->ratio);
                    break;
                case 'File':
                    
                    break;
                case 'Video':
                    dc($media->mediable->length);
                    break;
            } 
            
            //view blade
            include('media.'.class_basename($medium->mediable_type).'',[$media=>$media->mediable])
    }
05 May
2 years ago

t0ne started a new conversation Pattern For Media Library

I need the right pattern for a media library, this is my db setup: media table

  • id
  • path
  • size
  • etc. image table
  • id
  • media_id
  • orientation
  • width
  • height
  • etc. video table
  • id
  • media_id
  • duration

I want to use it like this: //controller: $media->store(new Image); $media->store(new File); or $media->image->store(); $media->video->store(); or ?? How should i setup my model structure? Models: Media - shared properties

  • Image
    • specific properties
  • File
    • specific properties
  • Video
    • specific properties
25 Apr
2 years ago

t0ne started a new conversation Sort And Paginate Eloquent Relationship

best solution to sort collection with relationship

i sort and paginate eloquent objects with relationship like this:

$collection = Object::with(['relation'])->where('foo','bar')->get();
$collection = $collection->sortByDesc('relation.published_at');
$collection->values()->all();
$collection = $this->getPaginator($collection, $perPage);

(i prefer this because of returned object '$collection->relation->column_names')

But i was wondering how this solution compares to the 'join sql' solution.

$collection = Object::join('relation')
    ->orderBy('relation.published_at', 'desc')
    ->where('foo','bar')
    ->paginate($perPage);

this returns $collection->column_names which i don't like.

I mean which solution has the better performance?

t0ne left a reply on Collection - OrderBy / SortBy

i also use @zachleigh suggested solution to sort collections like this: (because of returned object '$collection->relation->column_names')

$collection = Object::with(['relation])->where('foo','bar')->get();
$collection = $collection->sortByDesc('relation.published_at');
$collection->values()->all();
$collection = $this->getPaginator($collection, $perPage);

But i was wondering how this solution compares to the 'join sql' solution.

$collection = Object::join('relation')->orderBy('relation.published_at', 'desc')->where('foo','bar')->paginate($perPage);

this returns $collection->column_names which i don't like.

I mean which solution has the better performance?

28 Jan
2 years ago

t0ne left a reply on UserRoles Vs MiddleWare And Policy

thanks for your reply! makes sense, and that is what i need.

BUT... How can i use this in a controller or blade, for example:

//controller:
if (Gate::allows('view.user',$user)) {}
//blade:
@can('view.user',$user)

Or do i also have to create a policy to make this work?

routes.php uses MiddleWare and controller/view uses Policy?

t0ne left a reply on Best Way To Overwrite Option Method From Laravel 5 FormBuilder Class?

thanks to @chrisrebacz, thanks!!

    /**
     * Register the form builder instance.
     */
    protected function registerFormBuilder()
    {
        //bindShared
        $this->app->singleton('form', function($app)
        {
            $form = new FormBuilder($app['html'], $app['url'], $app ['view'], $app['session.store']->getToken());

            return $form->setSessionStore($app['session.store']);
        });
    }

    /**
     * Register the html builder instance.
     */
    protected function registerHtmlBuilder()
    {
        $this->app->singleton('html', function($app)
        {
            return new HtmlBuilder($app['url'],$app['view']);
        });
    }
27 Jan
2 years ago

t0ne left a reply on Best Way To Overwrite Option Method From Laravel 5 FormBuilder Class?

try to use this in laravel 5.2, but get error:

ErrorException in HtmlServiceProvider.php line 47: Fatal error: Call to undefined method Illuminate\Foundation\Application::bindShared()

changed "$this->app->bindShared" to "$this->app->singleton"

now i get:

ErrorException in HtmlBuilder.php line 39: Type error: Argument 2 passed to Collective\Html\HtmlBuilder::__construct() must implement interface Illuminate\Contracts\View\Factory, none given,

t0ne left a reply on UserRoles Vs MiddleWare And Policy

thanks for your reply!

I still don't fully understand, hope you can help me out: i created 'App\Policies\RolePolicy'

class RolePolicy
{ 
    public function editProfile(User $auth_user, User $edit_user){
       return false;
    }
}

edited AuthServiceProvider:

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
         User::class => UserPolicy::class
    ];

And now i can use it in my controller and blade files

//controller:
if (Gate::allows('editProfile',$user)) {}
//blade:
@can('editProfile',$user)

That's fine i guess;)

BUT: I also want to do check in the routes.php file, like:

Route::put('user/editProfile/{id}', ['middleware' => 'role:manager', function ($id) {

How can i RoleMiddleware make use of the RolePolicy?

t0ne started a new conversation UserRoles Vs MiddleWare And Policy

I want to use UserRoles to protect my routes.

For example: only managers can add a user.

So i can create a RoleMiddleware and use "middleware' => 'role:manager" in my routes.php.

But also want to use Roles in blade (or a Model) so i can disable/hide a link if (manager) {}

Now i need Authorization and create something like RolePolicy.

So i want to protect my routes and blade with the rule.

Do i need to create a MiddleWare AND a Policy, is this good practice?

03 Nov
3 years ago

t0ne left a reply on Why Use Polymorphic Relation Here

check, thanks for your effort!

t0ne left a reply on Why Use Polymorphic Relation Here

aha! so you can retrieve a collection of different objects yes?

t0ne left a reply on Why Use Polymorphic Relation Here

@pmall oke, have some patience with me please;) almost get it...

but i can get the related objects by $media->images or $media->videos

Class Media{
    public function videos(){
        $this->hasMany('App\Video')
    }
}

Class Video{
    public function media(){
        $this->belongsTo('App\Media')
    }
}

t0ne left a reply on Polymorphism?

@cristian9509 exactly what i would like to know! i feel like i can solve everything with foreign keys and pivot tables, what do i miss here!?

t0ne started a new conversation Why Use Polymorphic Relation Here

I've got a question about @martinbean 's best answer: https://laracasts.com/discuss/channels/general-discussion/hasmany-but-hasmany-could-contain-different-models?page=1#reply-111744

Why use a polymorphic relation for the Media, Image and Video models. What is the benefit over a normal db relation (FK) in this case: Image.media_id(fk) an Video.media_id(fk).

t0ne left a reply on HasMany But HasMany Could Contain Different Models

Why use a polymorphic relation for the Media, Image and Video models. What is the benefit over a normal db relation (FK): Image.media_id(fk) an Video.media_id(fk). ($game->media->images and $game->media->videos)

t0ne left a reply on Polymorphics Relations Or Regular?

i also would like to know

02 Nov
3 years ago

t0ne left a reply on Repo Pattern

oke thank you both!

t0ne left a reply on Repo Pattern

@pmall you agree with @zachleigh's answer?

t0ne left a reply on Repo Pattern

@zachleigh thanks! And "because we bound the interface to a concrete class" it's not polymorphism? When the interface is not bound to a concrete class (no service provider register) it can be polymorphism?

t0ne left a reply on Repo Pattern

good question, makes me think

interface IUserRepository 

class UserRepo implements IUserRepository

class UserMockRepo implements IUserRepository

class UserRedisRepo implements IUserRepository
class UserController extends BaseController {
    // IUserRepository is the interface
    public function __construct(IUserRepository $user) //Dependency Injection, polymorph can be an object which implements IUserRepository
    {
        $this->user = $user; //program to an interface
    }

in general: is this a repository pattern?

about the constructor:

  1. That's called de Dependency Injection right?
  2. Is this polymorphism? It can be any (different) object which implements IUserRepository
  3. $this->user is an interface which we can program to (?)

t0ne started a new conversation Repo Pattern

To be sure: does the repository pattern fit in the program to interface, polymorphism principle?

thanks in advance!

30 Oct
3 years ago

t0ne left a reply on Different Models Based On Table Column, All Extending A Base Model

@pmall you mean one media db table? how about specific properties like pixel_width etc?

t0ne left a reply on Different Models Based On Table Column, All Extending A Base Model

Gonna try this, thanks for your effort

20 Oct
3 years ago

t0ne left a reply on Retrieve Related And Non Related Items ManyToMany

oke;) what would you do?

t0ne left a reply on Retrieve Related And Non Related Items ManyToMany

It works, thanks a lot!

I now use the '$unrelated_components' part my controller. How should i refactor this? Should i add a unrelatedComponents method to my Template model?

trying to be a good developer here;)

t0ne started a new conversation Retrieve Related And Non Related Items ManyToMany

DB::tables:

Templates (table) -id -etc

Components (table) -id -etc

component_template (pivot table) -template_id (FK) -component_id (FK) -order_by_number

Class Template extends Model{

    public function components(){
        return $this->belongsToMany('App\Component')->withPivot('order_by_number')->orderBy('order_by_number','ASC');
    }
}

Class Component extends Model
{
    public function templates(){
        return $this->belongsToMany('App\Template');
    }
}

TemplateController:

$templates = Template::with(['components' => function($q) {
}])->get();//->get()

dd($templates);

returns:

Template Collection with -> related Component Collection

How do retrieve a TemplateCollection with related ComponentCollection AND a NON RELATED ComponentCollection:

Template Collection with -> related Component Collection (exists in pivot table) -> related Component Collection (does not exists in pivot table)

Is there something like belongsNotToMany?

19 Oct
3 years ago

t0ne left a reply on Need Advice On Eloquent Relationship

what @CImrie said, very important. check the sql that's generated by your methods. I use barry's debugbar a lot for debugging.

16 Oct
3 years ago

t0ne left a reply on Relationship Advice (no Pun Intended :-P)

shouldn't it be belongsTo relation? because player_deck_id, opponent_deck_id are foreign keys

t0ne left a reply on Need Advice On Eloquent Relationship

I'm just learning laravel (so keep that in mind;))

But this is my solution:

Class Leaves extends Model{

    public function user(){
        return $this->belongsTo('App\User');//user_id = FK, inverse of hasOne
    }
    
    public function leaveType(){
        return $this->belongsTo('App\LeaveType');//leave_type_id = FK, inverse of hasOne
    }
}

class LeaveType extends Model{  
    public function leave(){
        return $this->hasMany('App\Leaves');//one to many
    }

}

class User extends Model{   
    public function leave(){
        return $this->hasMany('App\Leaves');//one to many
    }

}

In your controller:

Use eager nested(!) loading:

$user = Users::with('leave.leaveType')->find(1);

$user returns a 
User Collection with 
    -> nested Leave Collection with 
        -> nested LeaveType Collection

dd($user);

$user->leave[0]->leaveType->name

$sitemap = Users::with(['leave' => function($q) {  // 1 query for leaves with...
    $q->whereHas('leaveType', function ($q) { // ...1 subquery to filter the leaveTypes by related type name
        $q->where('name', 'foo');
    });
}])->paginate(30);//->get()

P.S. the relations that SLow Loris uses in the Leave Model don't make any sense to me, could be me ofcourse..

14 Oct
3 years ago

t0ne started a new conversation Set The Request Value

ParameterBag {#329 ▼ #parameters: array:8 [▼ "_token" => "ythP0e9YfLlO0ZJHoLy3gnwiqUIt3tgBiHr28VhA" "system_name" => "asdfasdff" "parent_id" => "10" "online" => "1" "active_language_tab" => "nl" "translations" => array:5 [▼ "nl" => array:5 [▼ "id" => "" "sitemap_id" => "" "locale_id" => "" "name" => "asdf" "slug" => "sadf" ] "en" => array:5 [▶] "de" => array:5 [▶] "fr" => array:5 [▶] "es" => array:5 [▶] ] "created_by_user_id" => 1 "updated_by_user_id" => 1 ] }

how do i (re)set the request value of "translations > nl > id"? for example this works: $request->request->set('online',10000);

but something like this won't: $request->request->set('translations.'.$key.'.locale_id',$created_sitemap->translations[$key]->locale_id);

when i do: $request->translations[$key]['nl'] = insertID; i get "Indirect modification of overloaded property App\Http\Requests\SitemapRequest::$translations has no effect"

10 Oct
3 years ago

t0ne left a reply on Break, Continue, Return In Blade Template

why do we use blade again?

08 Oct
3 years ago

t0ne left a reply on Update User: Allow Blank Password

big miscommunication from my part sorry!