wizjo

wizjo

Member Since 2 Years Ago

Bielawa

Experience Points
51,010
Total
Experience

3,990 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
478
Lessons
Completed
Best Reply Awards
0
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.

Level 11
51,010 XP
Sep
08
2 months ago
Activity icon

Replied to Counting Expenses For Categories Stored In Tree Like Array

Sorry, but your reply is totally offtopic, as usual, so please dont spam more.

Activity icon

Started a new Conversation Counting Expenses For Categories Stored In Tree Like Array

I have an app where users can store their expenses and assign it to categories. Categories have tree structure, without depth limit and users can assign expense to any category (children, parent or middle). What I want to do is to count sum of expenses for all categories in tree structure. Lets simplify things and assume I have array with categories:

$categories = [
    0 => [
        'id' => 1,
        'name' => 'Car',
        'expenses_sum' => 0,
        'subcategories' => [
            0 => [
                'id' => 2,
                'name' => 'Gas',
                'expenses_sum' => 0,
                'subcategories' => [
                    0 => [
                        'id' => 3,
                        'name' => 'Orlen',
                        'expenses_sum' => 300,
                        'subcategories' => [
                            0 => [
                                'id' => 4,
                                'name' => 'Orlen A',
                                'expenses_sum' => 100,
                                'subcategories' => []
                            ],
                            1 => [
                                'id' => 5,
                                'name' => 'Orlen B',
                                'expenses_sum' => 100,
                                'subcategories' => []
                            ], 
                        ],
                    ],                                               
                ],
            ],                    
        ],
    ],       
];

What I want do do is to go to the deepest level ("Orlen A" and "Orlen B"), sum expenses from that level, add it to the parent level ("Orlen") and store as the new "expenses_sum", so it should be: 100 + 100 + 300 = 500 and repeat it to the top level.

My code to do that looks like this:

function sumCategory(&$category) {
    if (isset($category['subcategories'])) {
        foreach ($category['subcategories'] as $subCategory) {
            $subCategory['expenses_sum'] = sumCategory($subCategory);
            $category['expenses_sum'] += $subCategory['expenses_sum'];
        }
    }

    return $category['expenses_sum'];
}


foreach ($categories as $index => $category) {
    $categories[$index]['expenses_sum'] = sumCategory($category);
}

echo '<pre>';
print_r($categories);
echo '</pre>';

Code counts properly sum at all levels, but the problem is that finally I got $categories array with modfied only "expenses_sum" at the top level and categories in the middle stays not modified. I tried to pass $categories to function by refference, but it doesnt help. Any tips what should I correct?

I have simplified problem, so you can easily grab all above code to test things on your own.

Jun
22
4 months ago
Activity icon

Replied to Append An Attribute To Collection Without Causing N+1 Issue

Get collection like this:

$events = Event::with('attendees')->where('start_date', '>', now())->paginate(30);
Jun
18
4 months ago
Activity icon

Replied to Get Sum Of Expenses From Given Month Grouped By Categories

Sorry, but it still doesn't help me much and answers my question. You gave me query examples and this topic isn't about query. I wrote in my previous post exact query which gaves me data I need. Secondly you gave me simple foreach loop example that doesn't have anything in common with reccurency calculations I need...

Jun
17
4 months ago
Activity icon

Replied to Get Sum Of Expenses From Given Month Grouped By Categories

@jlrdw : I dont think this topic answers my question because I dont have problem with db schema and even getting data from database, but rather with preparing it to needed format, using recurrency.

I can easily get all data I need this way:

Category::with('expenses')->whereHas('expenses', function ($query) use ($month, $year) {
    $query->whereMonth('created_at', '=', $month)->whereYear('created_at', '=', $year);
})->get();

which gives me something like this:

Category {#2781 ▼
  #table: "categories"
  #fillable: array:2 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:6 [▼
    "id" => 1
    "parent_id" => null
    "name" => "Koszty"
    "deleted_at" => null
    "created_at" => "2018-01-13 17:14:58"
    "updated_at" => "2018-01-13 17:14:58"
  ]
  #original: array:6 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "expenses" => Collection {#2823 ▼
      #items: array:1 [▼
        0 => Expense {#2820 ▼
          +fillable: array:8 [▶]
          #with: array:1 [▶]
          #dates: array:2 [▶]
          #connection: "mysql"
          #table: "expenses"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:10 [▼
            "id" => 650
            "parent_id" => null
            "is_bill" => 0
            "amount" => 21.98
            "name" => "FS 20056/05/2019"
            "bill_number" => null
            "warranty_at" => null
            "notes" => "<p>3 &#322;adowarki USB-C</p>"
            "created_at" => "2019-05-24 18:30:55"
            "updated_at" => "2019-05-24 18:30:55"
          ]
          #original: array:13 [▶]
          #changes: []
          #casts: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:2 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
      ]
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}

What I need is to display sum of expenses for each category in a way i described in first post.

Jun
15
4 months ago
Activity icon

Started a new Conversation Get Sum Of Expenses From Given Month Grouped By Categories

I have a module where user can add expenses and assign them to one or more categories. Categories have a tree structure, and therefore children and parents.

I would like to display within the given month the tree structure of categories and for each category sum of expenses, something like this:

  • Car: 1000 //one of expenses for value of 100 assigned directly to "Car" category, so the sum for this category is: 100 + 700 + 200
    • Gas: 700
    • Repairs: 200
  • Bills: 400
    • Electricity: 200
    • Phones: 200

My models: App\Category.php:

protected $fillable = [
    'parent_id', 'name'
];

//--- RELATIONS ---

public function parent() {
    return $this->belongsTo('App\Category', 'parent_id');
}

public function children() {
    return $this->hasMany('App\Category', 'parent_id')->with('children');
}

public function expenses()
{
    return $this->morphedByMany('App\Expense', 'categorable');
} 

App\Expense.php:

public $fillable = [
    'amount', 'created_at'
];

protected $with = ['categories'];

//--- RELATIONS ---

public function parent() {
    return $this->belongsTo('App\Expense', 'parent_id');
}    

public function children() {
    return $this->hasMany('App\Expense', 'parent_id')->with('children');
}    

public function categories()
{
    return $this->morphToMany('App\Category', 'categorable');
}

The problem is that expense could be assigned not only to child categories, so I'm confused how to optimally calculate and show it.

Jun
08
5 months ago
Activity icon

Replied to Get Sum Of Invoices From Last 2 Years Grouped By Year And Month

Ok, I found finally solution (to my second question):

$invoices = DB::table('invoices')
    ->select(
        DB::raw('YEAR(created_at) as year'),
        DB::raw('MONTH(created_at) as month'),
        DB::raw('SUM(gross_price_sum) as sum')
    )
    ->whereYear('created_at', '=', Carbon::now()->year)
    ->orWhereYear('created_at', '=', Carbon::now()->subYear()->year)
    ->groupBy('year', 'month')
    ->get();      

In addition to that @cronix rightly noticed that there is no way to get from database data formatted the way I want:

The format is just how sql returns data, in or out of laravel. If you want it formatted differently, yes, you'd have > to loop over it and adjust as needed. You can't fix that with a different query.

Jun
06
5 months ago
Activity icon

Replied to Get Sum Of Invoices From Last 2 Years Grouped By Year And Month

@msovani : That also gives me empty results

@jlrdw : I dont think it solves my question because I dont have problems with getting data, but I would like to get it in specific format.

Jun
05
5 months ago
Activity icon

Started a new Conversation Get Sum Of Invoices From Last 2 Years Grouped By Year And Month

For now I have the query:

$data = DB::table('invoices')
    ->select(
        DB::raw('YEAR(created_at) as year'),
        DB::raw('MONTH(created_at) as month'),
        DB::raw('SUM(gross_price_sum) as sum')
    )
    ->groupBy('year', 'month')
    ->get();     

which gives me output:

[
   {
      "year":2019,
      "month":1,
      "sum":10000
   },
   {
      "year":2019,
      "month":2,
      "sum":10000
   },
  //...
]

...but I would like to get it in another format:

[
  '2019': {
      1:100000,
      2:100000,
    //...
   },
  '2018': {
      1:100000,
      2:100000,
    //...
   },
  //...
]

My questions:

  1. I wonder if there is a more elegant way to do this than iterating over collection to map it to desired format
  2. How to add condition to get invoices only from the last 2 years? I have tried to add at first condition: ->where(DB::raw('YEAR(created_at) = 2019')) after ->select(), but it already gives me empty collection
Activity icon

Replied to Str::slug Capitalizin First Letters

Do like this:

public function setSlugAttribute($value)
{
    return $this->attributes['slug'] = ucfirst(Str::slug($value));
}
Jun
03
5 months ago
Activity icon

Replied to Share Data Between Views And Causes Migration Error

@snapey :

That is perfectly what I need. Small fix- it shoud be:

if (!app()->runningInConsole()) { //instead of: $app->

You also overtook my next question: about similiar topic with permissions. In linked topic there is a method app()->runningInTests() which seems not to a part of framework. How looks the body of that?

Activity icon

Replied to Share Data Between Views And Causes Migration Error

@Tray2 : Please read what I wrote at the beginning of this topic. It is the way I have now implemented it, but it causes problems with migrations.

Activity icon

Replied to Share Data Between Views And Causes Migration Error

@mushood

Unfortunately my error didnt change. I did this:

  1. make app\Providers\ComposerServiceProvider.php :
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
        view()->composer('*', function ($view) {
            $view->with([
                'all_users' => User::mostActive()->where('active', '=', 1)->get()->pluck('full_name_company_email', 'id'),
            ]);
        });
    }

    public function register()
    {
    }
}
  1. added new provider to config/app.php:
    'providers' => [
    //...
        
    App\Providers\ComposerServiceProvider::class,

    //...
    ],
  1. made composer dump-autoload command

I am pretty sure that application hits new provider file because at first it was small typo in your code listing, so I fixed it.

Activity icon

Started a new Conversation Share Data Between Views And Causes Migration Error

In my AppServiceProvider.php I have line to share users data between views:

public function boot()
{
    View::share('all_users', User::mostActive()->where('active', '=', 1)->get()->pluck('full_name_company_email', 'id'));
}

The problem is that this line cause error while doing migrations by php artisan migrate command:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.users' doesn't exist

...beacuse AppServiceProvider searches for table "users" before it is created by migrations.

Any ideas how to solve that?

Jun
01
5 months ago
Activity icon

Replied to Phpunit Configuration Refresh My Database

@tray2 & @dime_galev But, it is exactly what I have in my code and that cause problem with tests...

Activity icon

Replied to Phpunit Configuration Refresh My Database

@dime_galev & @tray2 :

I created fresh Laravel project and solved all migration problems (btw. it was quite strange that I have to change "foreign" method to "integer" in my migrations, otherwise I got an error), but when moving back my files to my root project the error doesn`t change.

Digging deeper I noticed that the problem was in AppServiceProvider.php with this line:

View::share('all_users', User::mostActive()->where('active', '=', 1)->get()->pluck('full_name_company_email', 'id'));

Commenting this out moves me one step further, so the error changes to almost the same, but concering another table:

In Connection.php line 664:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.permissions' doesn't exist (SQL: select * from `permissions`) In PDOConnection.php line 82:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.permissions' doesn't exist

In PDOConnection.php line 80:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.permissions' doesn't exist

I found out that commenting out the content of my app\Providers\AuthServiceProvider.php solves finally problems with migrations (runnig command: php artisan migrate):

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any application authentication / authorization services.
     *
     * @param  \Illuminate\Contracts\Auth\Access\Gate  $gate
     * @return void
     */
    public function boot(GateContract $gate)
    {
        parent::registerPolicies($gate);

        // Dynamically register permissions with Laravel's Gate.
        foreach ($this->getPermissions() as $permission) {
            $gate->define($permission->name, function ($user) use ($permission) {
                return $user->hasPermission($permission);
            });
        }
    }

    /**
     * Fetch the collection of site permissions.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    protected function getPermissions()
    {
        return Permission::with('roles')->get();
    }
}

...so now my tests run correctly, but I have additional 2 problems connected with code below which I have to comment out:

  1. How to share between all views data about all users in database (I need it for displaying select in my CRM which allows me to quick login to any user account).
  2. I have roles and permissions table and AuthServiceProvider needs tables to be already migrated.
May
31
5 months ago
Activity icon

Replied to Phpunit Configuration Refresh My Database

@tray2 : unsigned() at boolean seams not to be a problem

@dime_galev : I got error:

In Connection.php line 664:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.users' doesn't exist (SQL: select * from `user
  s` where `active` = 1 order by `activity_level` desc)


In PDOConnection.php line 82:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.users' doesn't exist


In PDOConnection.php line 80:

 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'wizjo_crm.users' doesn't exist

Perhaps a certain clue will be that I did not make migrations on a regular basis. At some point I stopped doing them and created tables "manually" in phpmyadmin. At the moment when someone said that I need migrations to tests - I created them. In addition, because I thought that the order of migrations may be significant, I manipulated the filenames so that those that according to me should be first (because others have indexes related to them) had the earliest dates in the names.

Here is the list of filenames of my migrations:

2018_01_09_203901_create_roles_table.php
2018_01_10_203901_create_users_table.php
2018_01_10_203902_create_companies_table.php
2018_01_10_205034_create_websites_table.php
2018_01_13_124753_create_company_user_pivot_table.php
2018_01_16_193644_create_issuers_table.php
2018_01_20_152514_create_project_user_pivot_table.php
2018_01_23_185307_create_tasks_table.php
2018_01_23_191128_create_task_user_pivot_table.php
2018_01_23_191221_create_comments_table.php
2018_11_20_235120_create_cache_table.php
2018_12_22_143752_create_meetings_table.php
2018_12_22_150250_create_meeting_types_table.php
2018_12_26_150607_create_expenses_table.php
2019_05_29_161218_create_projects_table.php
2019_05_29_161243_create_categorables_table.php
2019_05_29_161308_create_categories_table.php
2019_05_29_161348_create_files_table.php
2019_05_29_161414_create_invoices_table.php
2019_05_29_161437_create_invoice_positions_table.php
2019_05_29_161502_create_invoice_relations_table.php
2019_05_29_161530_create_jobs_table.php
2019_05_29_161624_create_permissions_table.php
2019_05_29_161725_create_procedures_table.php
2019_05_29_161816_create_reminders_table.php
2019_05_29_161857_create_statuses_table.php
2019_05_29_162026_create_valuations_table.php
2019_05_29_162106_create_permission_role_pivot_table.php
2019_05_29_162120_create_procedure_user_pivot_table.php
2019_05_29_162126_create_reminder_user_pivot_table.php
May
30
5 months ago
Activity icon

Replied to Phpunit Configuration Refresh My Database

@tray2 : As you can see in my code listing at the top that trait is already in code.

@dime_galev & @tisuchi Yes, I add some additional fields to it, but I dont see any place which could cause problems:

2018_01_10_203901_create_users_table.php

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('role_id')->references('id')->on('roles')->onDelete('cascade')->unsigned()->default(4);
            $table->string('name', 50)->nullable();
            $table->string('lastname', 50)->nullable();
            $table->string('email', 50)->nullable()->unique();
            $table->string('phone', 50)->nullable();
            $table->string('postal', 10)->nullable();
            $table->string('city', 200)->nullable();
            $table->string('address', 250)->nullable();
            $table->string('nip', 15)->nullable();
            $table->string('pesel', 15)->nullable();
            $table->integer('hour_rate')->unsigned()->nullable();
            $table->boolean('active')->unsigned()->default(1);
            $table->string('password', 191)->nullable();
            $table->text('notes')->nullable();
            $table->rememberToken();
            $table->integer('activity_level')->unsigned()->default(0);
            $table->timestamps();
        });
    }
May
29
5 months ago
Activity icon

Replied to Phpunit Configuration Refresh My Database

I fixed migrations and the error changed to:

1) Tests\Unit\ExampleTest::testBasicTest
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: users (SQL: select * from "users" where "active" = 1 order by "activity_level" desc)

The database is not resetetting anymore, so I suspect that the problem is that the testing database is empty. So the question is how to run migrations for it and shouldn`t it happen automatically when running tests?

May
28
5 months ago
Activity icon

Started a new Conversation Phpunit Configuration Refresh My Database

When I run phpunit --stop-on-failure command I got an error:

Tests\Unit\ExampleTest::testBasicTest
Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'project_id' doesn't exist in table (SQL: alter table `tasks` add constraint `tasks_project_id_foreign` foreign key (`project_id`) references `projects` (`id`) on delete cascade)

After that I noticed my database is missing most of the tables, so it looks like test makes database migration reset.

i cannot find the reason of that because:

  1. My configuration points to doing tests in memory
  2. Im running only default Laravel test

Here is my configuration:

phpunit.xml

<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite_testing"/>

config\database.php

    'connections' => [

        //...

        'sqlite_testing' => [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ],

    ],

default unit test - tests\Unit\ExampleTest.php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    use DatabaseMigrations;

    public function testBasicTest()
    {
        $this->assertTrue(true);
    }
}

Commenting out line use DatabaseMigrations; makes that database is not resetting, but it doesn`t solve the problem. Database for testing should be separate.

What am I missing?