wizjo

Member Since 2 Years Ago

Bielawa

Experience Points 47,720
Experience Level 10

2,280 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 446
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

17 Jun
1 day ago

wizjo left a reply on 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:

Collection {#2777 ▼
  #items: array:37 [▼
    0 => Category {#2818 ▼
      #table: "categories"
      #fillable: array:2 [▶]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [▶]
      #original: array:6 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "expenses" => Collection {#4009 ▼
          #items: array:1 [▼
            0 => Expense {#3960 ▼
              +fillable: array:8 [ …8]
              #with: array:1 [ …1]
              #dates: array:2 [ …2]
              #connection: "mysql"
              #table: "expenses"
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:10 [ …10]
              #original: array:13 [ …13]
              #changes: []
              #casts: []
              #dateFormat: null
              #appends: []
              #dispatchesEvents: []
              #observables: []
              #relations: array:2 [ …2]
              #touches: []
              +timestamps: true
              #hidden: []
              #visible: []
              #guarded: array:1 [ …1]
            }
          ]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => Category {#2819 ▶}
    2 => Category {#2820 ▶}
    3 => Category {#2821 ▶}
    //...
  ]
}

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

15 Jun
3 days ago

wizjo started a new conversation Get Sum Of Exepnses 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.

08 Jun
1 week ago

wizjo left a reply on 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.

06 Jun
1 week ago

wizjo left a reply on 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.

05 Jun
1 week ago

wizjo 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

wizjo left a reply on Str::slug With Uppercasing First Letter

Do like this:

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

wizjo left a reply on 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?

wizjo left a reply on 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.

wizjo left a reply on 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.

wizjo 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')); //EDIT: 01.06.2019     
    }

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?

01 Jun
2 weeks ago

wizjo left a reply on Phpunit Configuration Refresh My Database

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

wizjo left a reply on 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.
31 May
2 weeks ago

wizjo left a reply on 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
30 May
2 weeks ago

wizjo left a reply on 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();
        });
    }
29 May
2 weeks ago

wizjo left a reply on 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?

28 May
3 weeks ago

wizjo 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)

I noticed that 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?

08 Mar
3 months ago

wizjo started a new conversation Unverified User Should Not Be Able To Log In

By default, the mechanism to verify if the user has confirmed email, works in such a way that it logs in user, but does not allow him to visit routes, which have set middleware ('verified'). However, I would like to user not be able to log in until he has confirmed account.

I tried to add middleware in the routes.web.php file:

Route :: post ('login', 'Auth \ LoginController @ login') -> middleware ('verified');

The problem, however, is that then the VerificationController in the constructor runs $this->middleware ('auth'). If we comment it out, then the "show" method does not receive the "Request" parameter. VerificationController depends on authenticated user.

VerificationController.php:

    public function __construct ()
    {
        // $ this-> middleware ('auth');
        $ This-> middleware ( "signed") -> only (the verify ');
        $ this-> middleware ('throttle: 6.1') -> only ('verify', 'resend');
    }

    public function show (Request $ request)
    {
        dd ( '11111111111');
        if ($ request-> user () -> hasVerifiedEmail ()) {
            return redirect () -> route ('my_account');
        }

        return view ('auth.verify');
    }
25 Feb
3 months ago

wizjo left a reply on [SQL] Search In A Concatenated Fields

@Tray2: It works.

@staudenmeir : Bless you, that was solution =).

wizjo left a reply on [SQL] Search In A Concatenated Fields

@bobbybouwmann : I know about raw methods, but I dont know how to construct query which I need using that. It doesn`t matter if it will be through Eloquent or raw query. I just want it to work :).

@staudenmeir : Doing like that I got empty results.

wizjo started a new conversation [SQL] Search In A Concatenated Fields

I have query like this:

       $payments = DB::table($tableName)
            ->leftJoin('users', $tableName.'.user_id', '=', 'users.id')
            ->leftJoin('subscription_plans', $tableName.'.subscription_plan_id', '=', 'subscription_plans.id')
            ->select(
                DB::raw("CONCAT(users.firstname, ' ', users.lastname) AS user")
                , 'subscription_plans.name as subscription_plan'
                , $tableName.'.order_id'
                , $tableName.'.gross_price'
                , $tableName.'.status'
                , $tableName.'.created_at'
            )
            ->where('user', 'like', 'Bartłomiej')
            ->orderBy('user', 'DESC')
            ->get();

Im concatenating "firstname" and "lastname" as "user" and later on I would like to search using "%LIKE%" in all columns, including concatened, but I`m getting this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user' in 'where clause' (SQL: select CONCAT(users.firstname, ' ', users.lastname) AS user, `subscription_plans`.`name` as `subscription_plan`, `payments`.`order_id`, `payments`.`gross_price`, `payments`.`status`, `payments`.`created_at` from `payments` left join `users` on `payments`.`user_id` = `users`.`id` left join `subscription_plans` on `payments`.`subscription_plan_id` = `subscription_plans`.`id` where `user` like Bartłomiej order by `user` desc)
22 Nov
6 months ago

wizjo left a reply on Right Strategy To Save User Generated Content?

Yes, it does. From documentation:

https://laravel.com/docs/5.7/queries#introduction:

The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

So, there is no need to use any external packages for that. You can only validate user input (https://laravel.com/docs/5.7/validation#form-request-validation) to make sure you got from user data in an expected type.

21 Nov
6 months ago

wizjo left a reply on Right Strategy To Save User Generated Content?

Laravel filters it for you, so you dont have to worry about any injections. In addition, you can create rules for filtering fields according to your needs: https: //laravel.com/docs/5.7/validation#form-request-validation

wizjo left a reply on Removing Password Confirmation

Show your app\Http\Controllers\Auth\ResetPasswordController.php file.

In that file you should add.change rules() method to something like this:

    protected function rules()
    {
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:6',
        ];
    }

wizjo left a reply on Can I Use Algorithms In Laravel Or In Database Or In Web Development In General

Laravel is a framework, so treat it as ready-to-go set of common, usefull functions. The algorithm in turn is a well-defined way to solve a specific problem. In a good framework you can expand default functionality as you want using your own piece of code or using another words- alghoritms. However, common issues are usually written in frameworks in a very optimal way, using design patterns, which are a proven way to solve a specific problem.

wizjo left a reply on Repopulating Old Input Of Array Form

<form>
    <input name="first" value="{{ old('first') }}"/>
    <input name="second" value="{{ old('second') }}"/>
</form>

//you can check if errors exists this way:
@if (count($errors) > 0)

@endif

//or if you are using Form facade (Collective\Html\FormFacade::class) you can use form binding:
{{ Form::model($task, ['route' => array('zadania.update', $task->id), 'method' => 'PUT']) }}
    {{ Form::text('first', null, ['class' => 'something', 'required' => 'required']) }}
    {{ Form::text('second', null, ['class' => 'something', 'required' => 'required']) }}
{{ Form::close() }} 

wizjo left a reply on Debugbar Shows Thousands Gate Queries

I have some assumptions that I need to check in the subject of delay, but in order not to leave the main topic, the proposal is probably as I wrote in the previous post- the @can directive does not cause unnecessary database queries or excessive delays, so it can be used safely and there is nothing to worry about using it in loops and the number of uses is not very significant.

wizjo left a reply on Debugbar Shows Thousands Gate Queries

@gertjanroke : It is only 1s delay.

@cronix : Yes, my suspicion was the same, so I think we can draw a conclusion that there's nothing to worry about and using @can directive doesnt reduce performance as well as using @if doesnt.

I do not understand why in this case such statistics exists for, since it doesn`t brings nothing important.

20 Nov
6 months ago

wizjo left a reply on DoesntHave With OrWhere In Query

Perfect! That`s it.

For future reference. This is complete query:

            $projects = Project
                ::with('tasks.status', 'tasks.users')
                ->where(function ($query) use ($currentUser) {
                    $query->whereHas('users', function ($query) use ($currentUser) {
                        $query->where('users.id', '=', $currentUser->id);
                    })
                    ->whereHas('tasks.users', function ($query) use ($currentUser) {
                        $query->where('id', '=', $currentUser->id);
                    });
                })
                ->orDoesntHave('tasks.users')
                ->get(); 

wizjo left a reply on Debugbar Shows Thousands Gate Queries

@CRONIX - @click : About caching: I have changed my UserController index method to:

    public function index() {
        if (!Auth::user()->can('users-general-access')) { return Redirect::to('zadania'); }

        $users = Cache::rememberForever('users', function () {
            return User::with('role')->get();
        });

        return view('osoby.index')->with([
            'users' => $users,
        ]);
    }

and I dont see any big difference beside reducing 6 queries to 3.

@Cronix : Here is my index.blade.php view:

@section('width', 'fullwidth')
@extends('layouts.app')

@section('title', 'Osoby')

@section('submenu')
    @include('osoby.partial.submenu')   
@endsection

@section('modals')
    @include('partial.modals.delete')
@endsection 

@section('content')
    @hasSection('width')
    <section class="content container-fluid">
    @else
    <section class="content container">
    @endif  
    <div class="row">
        <div class="col-xs-12">
            <h1 class="page-header">Osoby</h1>      
        </div>
    
        <div class="col-xs-12">
            @include('partial.errors')  

            @can('users-add')
            <a class="btn" href="{!! URL::to('osoby/create') !!}">Dodaj osobę</a>
            @endcan
    
            <table id="main-table" class="table table-striped table-bordered" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Imię i nazwisko</th>
                        <th>E-mail</th>
                        <th>Telefon</th>
                        <th>Zawieszony</th>
                        <th>Rola</th>
                        @canany('users-edit|users-delete|users-lock')<th></th>@endcanany
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>Imię i nazwisko</th>
                        <th>E-mail</th>
                        <th>Telefon</th>
                        <th>Zawieszony</th>
                        <th>Rola</th>
                        @canany('users-edit|users-delete|users-lock')<th></th>@endcanany
                    </tr>
                </tfoot>
                <tbody>
                @foreach($users as $key => $value)
                    <tr>
                        <td class="{{ $value->statusLock() }}"><a href="{{ URL::to('osoby/' . $value->id . '/edit') }}">{{ $value->fullName }}</a></td>
                        <td class="{{ $value->statusLock() }}">{{ $value->email }}</td>
                        <td class="{{ $value->statusLock() }}">{{ $value->phone }}</td>                 
                        <td class="{{ $value->statusLock() }}">{{ ($value->active) ? 'nie' : 'tak' }}</td>
                        <td class="{{ $value->statusLock() }}">
                            @if ($value->role)
                                {{ $value->role->label }}
                            @endif
                        </td>
                        @canany('users-edit|users-delete|users-lock')
                        <td class="nowrap">
                            @can('users-edit')
                                <a class="table-ico" href="{{ URL::to('osoby/' . $value->id . '/edit') }}"><img src="{{ URL::asset('img/ico-edit.png') }}" alt="" /></a>
                            @endcan
                            
                            @can('users-delete')
                                <a class="table-ico modal-open modal-open-delete" data-modal="modal-delete-form" data-id="{{$value->id}}"><img src="{{ URL::asset('img/ico-delete.png') }}" alt="" /></a>
                            @endcan
                            
                            @can('users-lock')
                                <a class="table-ico" href="{{ URL::to('osoby/' . $value->id . '/lock') }}" title="
                                @if($value->active == 1)
                                    Zablokuj osobę (nie będzie mógł do czasu odblokowania logować się do systemu)
                                @else
                                    Odblokuj osobę
                                @endif
                                "><img src="{{ URL::asset('img/ico-lock.png') }}" alt="" /></a>
                            @endcan
                        </td>
                        @endcanany
                    </tr>               
                @endforeach             

                </tbody>
            </table>
            <script>
                $(document).ready(function() {
                    $('#main-table').dataTable({
                        "language": {
                            "processing":     "Przetwarzanie...",
                            "search":         "Szukaj:",
                            "lengthMenu":     "Pokaż _MENU_ pozycji",
                            "info":           "Pozycje od _START_ do _END_ z _TOTAL_ łącznie",
                            "infoEmpty":      "Pozycji 0 z 0 dostępnych",
                            "infoFiltered":   "(filtrowanie spośród _MAX_ dostępnych pozycji)",
                            "infoPostFix":    "",
                            "loadingRecords": "Wczytywanie...",
                            "zeroRecords":    "Nie znaleziono pasujących pozycji",
                            "emptyTable":     "Brak danych",
                            "paginate": {
                                "first":      "Pierwsza",
                                "previous":   "Poprzednia",
                                "next":       "Następna",
                                "last":       "Ostatnia"
                            },
                            "aria": {
                                "sortAscending": ": aktywuj, by posortować kolumnę rosnąco",
                                "sortDescending": ": aktywuj, by posortować kolumnę malejąco"
                            }
                        },                  
                        
                        "pageLength" : 100,
                        "order" : [[3, 'asc'], [4, 'desc']],
                    });
                    
                    $('body').on('click', 'a.modal-open-delete', function() {
                        project_id = $(this).data("id");
                        
                        action = '<?php echo URL::to('osoby'); ?>/'+project_id;
                        $('#delete-form').attr('action', action);                       
                    });                     
                });
            </script>
        </div>
    </div>
</section>
@endsection

wizjo left a reply on Debugbar Shows Thousands Gate Queries

Debugbar shows only 6 queries, so I`m not sure if this is clue of problem:

select * from `users` where `id` = '1' limit 1 //public\index.php:54

select * from `roles` where `roles`.`id` in ('1') //public\index.php:54

select `permissions`.*, `permission_role`.`role_id` as `pivot_role_id`, `permission_role`.`permission_id` as `pivot_permission_id` from `permissions` inner join `permission_role` on `permissions`.`id` = `permission_role`.`permission_id` where `permission_role`.`role_id` in ('1') //public\index.php:54

select * from `users`//app\Http\Controllers\UserController.php:24

select * from `roles` where `roles`.`id` in ('1', '2', '3', '4') //app\Http\Controllers\UserController.php:24

select `permissions`.*, `permission_role`.`role_id` as `pivot_role_id`, `permission_role`.`permission_id` as `pivot_permission_id` from `permissions` inner join `permission_role` on `permissions`.`id` = `permission_role`.`permission_id` where `permission_role`.`role_id` in ('1', '2', '3', '4')

I also added just now:

protected $with = ['role']; //to User model

protected $with = ['permissions']; //to Role model

but it didnt affect with reducing "gate" number.

wizjo started a new conversation DoesntHave With OrWhere In Query

I need to build query in which I will get projects with tasks that:

(current user belongs to project && project has tasks that are assigned to current user) or (project has tasks that are not assigned to anyone).

I stuck with this query:

            $projects = Project
                ::with('tasks.status', 'tasks.users')
                // this should be first condition where(
                ->whereHas('users', function ($query) use ($currentUser) {
                    $query->where('users.id', '=', $currentUser->id);
                })
                ->whereHas('tasks.users', function ($query) use ($currentUser) {
                    $query->where('id', '=', $currentUser->id);
                })
                // ) end firstwhere
                ->doesntHave('tasks.users') //this should be wrap into orWhere
                ->get();  

wizjo started a new conversation Debugbar Shows Thousands Gate Queries

In my application, I have users, from whom everyone can have one role, and role has many permissions.

I store permissions in database and attach it to roles.

Recently I have installed great package Debugbar (https://github.com/barryvdh/laravel-debugbar) which shows me in some views (for example users listing page) an alarmingly large number (over 2000) in Gate tab.

This number is connected with using @can directive in Blade views.

I wonder if this is a sign that something is worth optimizing, because it slows down my application or is it normal and the use of such directives is the optimal solution.

I'm not sure if this will be needed to recognize the problem, but I also paste a few places from my role-related code:

Trait HasRoles used in User model

trait HasRoles
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function hasRole($roles)
    {
        if (count($roles) > 0) {
            foreach ($roles as $role) {
                if ($role->name == $this->role->name) {
                    return true;
                }
            }

            return false;
        }

        return ($this->role->name == $roles);
    }

    public function hasPermission(Permission $permission)
    {
        return $this->hasRole($permission->roles);
    }
}
02 Nov
7 months ago

wizjo left a reply on Get Project Valuation Using WhereHas And OrHas

Yes, I have, so what exactly do you suggest?

wizjo left a reply on Get Project Valuation Using WhereHas And OrHas

Nope, no difference...

wizjo started a new conversation Get Project Valuation Using WhereHas And OrHas

I have a task app where users can add Tasks which belongs to Projects. Each task can have many Valuations (additional payment for) and also Comments which can have also Valuations.

So relations looks like this:

  • project.tasks.valuations
  • project.tasks.comments.valuations

Now Im trying to show in sidebar all valuations from current project, so I would like to get only tasks which have valuations or comments with valuations.

Here is the query on which I got stuck:

        $valuations = Project
            ::with('tasks.valuations', 'tasks.comments.valuations')
            ->where('id', $project_id)
            ->whereHas('tasks.valuations')
            ->orhas('tasks.comments.valuations')
            ->first();
  1. Unfortunately it returns also tasks which doesn`t have any valuations or comments with valuations.
  2. It would be perfectly if as result I will get collection with only valuations so, it would be easy to foreach it, but it is not necessary.
22 Oct
7 months ago

wizjo left a reply on Separate User Role Logic From Controller

Ok. It can be done like that. What do you think of making TaskController abstract class and prepare AdminTaskController, EmployerTaskController, CustomerTaskController which will extend it? Maybe this is the method of doing it the most clear way?

21 Oct
7 months ago

wizjo started a new conversation Separate User Role Logic From Controller

I have a task app and in my TaskController there is many logic, "if" and "switch" statements connected to user roles and permissions. It seems to me that such solution ceases to be optimal and I am thinking about better code organization and splitting into separate classes. Can anyone advise me how to do organize it in logic and clean way? Below are 2 example methods to illustrate problem.

TaskController:

    public function index($status_slug, $project_id) {  
        if (!Auth::user()->can('tasks-general-access')) { return Redirect::to('projekty'); }

        $currentUser = User::with(['projects', 'role'])->find(Auth::user()->id);

        if (!$currentUser->can('tasks-'.$status_slug)) { return Redirect::to('projekty'); }    

        $project = Project::with('users')->find($project_id);

        if (!$project->isAssignedTo($currentUser)) {
            return Redirect::to('projekty');
        }

        switch ($currentUser->role->name) {
            case 'customer':                
                $statuses = Status::withCount(['tasks' => function ($query) use ($project_id) {
                    $query->where('project_id', $project_id)->where('customer_visibility', 1);
                }])->get();

                break;
            default:
                $statuses = Status::withCount(['tasks' => function ($query) use ($project_id) {
                    $query->where('project_id', $project_id);
                }])->get();
        }

        
        $status = Status::where('slug', $status_slug)->first();     
        
        $tasks = Task::with('author', 'comments', 'files', 'users', 'status', 'valuations')
            ->where('status_id', $status->id)
            ->where('project_id', $project_id)
            ->orderBy('priority', 'DESC')
            ->get();    

        //valuations from all project statuses
        $valuations = Task::with('comments.valuations', 'valuations')
            ->where('project_id', $project_id)
            ->orderBy('priority', 'DESC')
            ->has('valuations')
            ->orHas('comments.valuations')
            ->get();    
        
        return view('zadania.index')->with([
            'project'       => $project,
            'projects'      => $currentUser->projects->where('finished', '=', null)->pluck('name', 'id')->toArray(),
            'statuses'      => $statuses,
            'valuations'    => $valuations,            
            'tasks'         => $tasks,
            'priorities'    => TaskPriority::all(),
            'status_slug'   => $status_slug,
            'project_id'    => $project_id,
            'current_user'  => $currentUser,
        ]);
    }
    
    public function create($project_id = null) {
        if (!Auth::user()->can('tasks-add')) { return Redirect::to('projekty'); }

        $currentUser = User::with(['projects', 'role'])->find(Auth::user()->id);
        
        switch ($currentUser->role->name) {
            case 'admin':
            case 'superadmin':
                $projects = Project::active()->pluck('name', 'id');
                $users = User::mostActive()->get()->pluck('full_name', 'id');
                $statuses = Status::all();

                break;
            case 'employer':
                $projects = $currentUser->projects->where('finished', '=', null)->pluck('name', 'id');
                $users = User::mostActive()->whereIn('role_id', [1, 2, 3])->get()->pluck('full_name', 'id'); //superadmins, admins, employers
                $statuses = Status::employerCreate()->get();

                break;
            case 'customer':                
                $projects = $currentUser->projects->pluck('name', 'id');
                $users = [];
                $statuses = Status::customerCreate()->get();

                break;
        }

        return view('zadania.create')->with([
            'projects'      => $projects,
            'users'         => $users,
            'statuses'      => $statuses,
            'priorities'    => TaskPriority::all(),
            'project_id'    => $project_id,
            'current_user'  => $currentUser,
        ]);
    }       
28 Aug
9 months ago

wizjo started a new conversation How To Apply Polymorphism/interface?

I have an application through which users can upload photos, process them, and then order (photos, mugs, etc.). As part of the application for various products, there is a common FileController, which is responsible for ajax adding files. There is now a need to change code so that for different product types the filename could vary. I think it is a flagship example of using polymorphisms / interfaces, but although I know the theory, I do not know how to change the code in this case. How organize class files and switch getName() method to specific product implementation?

FileController:

class FileController extends Controller
{
    public static function store(FileRequest $request) {
        dd($request->toArray());
        $file = $request->file('file');
        $filename = $this->getName(); // <- I 
        $extension = $file->guessExtension();
        

        $photo = new File([
            'name'              => $file->getClientOriginalName(),
            'extension'         => $file->guessExtension(),
            'path'              => $file->storeAs('files/'.$request->path, $filename.'.'.$extension, 'public'),
            'fileable_type'     => 'App\'.$request->fileable_type,
        ]);
        
        $path =  public_path('storage/'.$photo->path);
        list($photo->width, $photo->height) = getimagesize($path);

        $photo->save();
        
        return $photo;
    }
    
    private function getName() {
        return str_random(30);
    }
}

My getName() method for a PhotoPrint type of product (I dont know in which file put it and how execute it):

    private function getName($request) {
        $filename = '';
        
        if ($request->photo_effect) {
            if ($request->photo_effect) {
                switch($request->photo_effect) {
                    case 'sepia':
                        $filename = 'sepia_';
                        break;
                    case 'grayscale':
                        $filename = 'czarno-biale_';
                        break;                                          
                    default:
                        break;
                }   
            }           
        }
        
        $filename .= str_random(30);
        
        return $filename;
    }

routes.php

Route::post('pliki', 'Frontend\[email protected]');

Should I change FileController to be an interface and PhotoPrintFile will implement it? How then I can switch in my routes.php to use specific implementation?

01 Jun
1 year ago

wizjo left a reply on Database Structure For Managing Content With Different Page Templates

@martinbean: Yes, that`s right- it is the hardest part, however Im afraid that using such solution as Perk can be quite tricky, because Im not sure if admin panel would look like consistent. If not I wonder if using, for example Wordpress (which I know well), will be the better solution. Offcourse that is very unelegant and means that we have 2 separate admin systems.

It looks that there is no perfect solution and if I want to do it fairly quickly, then it would be necessary to compromise.

wizjo started a new conversation Database Structure For Managing Content With Different Page Templates

I have a page with subpages operating on different view templates. The client wants to have CMS for each of these subpages. In the case of simple subpages, the matter is simple because we only have fields to edit the title + content, but in the case of more complicated views, there are various sections and fields that are different for different subpage templates.

I wonder now what is the best strategy to prepare a database structure for this?

Should each template have a separate table in the database with columns corresponding to the edited fields or maybe it is better to json the content from different fields and save them into one column in the database?

In addition, in the admin panel for each type of subpage I need to prepare separate forms for editing, containing specific fields.

How do you usually deal with programming such things, so the code is as optimal and elegant as possible?

wizjo left a reply on Sending An Email To The Thread

@lostdreamer_nl : Your code works, emails have additional headers:

Sender: [email protected]
Message-ID: <[email protected]>
Date: Fri, 01 Jun 2018 09:00:26 +0200
Subject: Website name - Subject
From: "Website name" <[email protected]>
Reply-To: [email protected]
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="_=_swift_v4_1527836426_832e44a3fed175590477b41d801dba4b_=_"
References: [email protected]
In-Reply-To: [email protected]

but emails in recipient inbox are still most time not threaded. They are threaded only in situation when sender sends 2 or more messages in a row, not waiting for recpient respond.

30 May
1 year ago

wizjo left a reply on Sending An Email To The Thread

@lostdreamer_nl : When I use your code I get this error:

Call to a member function addTextHeader() on null

When I comment out the line:

->addTextHeader('In-Reply-To', $this->thread->hash.'@domain.pl')

I got another error:

Call to undefined method Swift_Message::from()

...so the errors are pretty same that in my code.

wizjo left a reply on Sending An Email To The Thread

@lostdreamer_nl: Thank you for that, but now Im struggling how to set that headers. For now I ended with this code:

    public function build()
    {
        $this->markdown('emails.inquiry');
        
        $this->withSwiftMessage(function ($message) {
            $message
                ->getHeaders()
                    // ->addTextHeader('In-Reply-To', $this->thread->hash.'@domain.pl')
                ->from('[email protected]')
                ->replyTo($this->thread->hash.'@domain.pl')                 
                ->addTextHeader('References', $this->thread->hash.'@domain.pl');
        });     
    }

but the problem is that it:

  1. doesn`t have "from" method: Call to undefined method Swift_Mime_SimpleHeaderSet::from()
  2. I can invoke addTextHeader only once because when I chain it twice it gives me error.

Do you have working example of such code or know what should I fix?

wizjo started a new conversation Sending An Email To The Thread

How can I send an email from Laravel so the recipient's inbox treat it as a part of the started aerlier thread, rather than a new, separate message?

Explaining in another way:

  1. Im sending message from Laravel which comes to the recipient e-mail.
  2. Recipient replies and I parse this message to the user inner website inbox. From there user can reply and message will go again to the recipient e-mail. The problem is that this message is a separate thread.

I am sending e-mails using the same informations as in the first e-mail:

  • topic
  • from
  • reply-to
29 May
1 year ago

wizjo left a reply on Get Companies In Range From User

Below I paste the correct query, which was a solution thanks to @Helmchen

        $companies = Company::whereRaw('
            ST_Distance_Sphere(
                point(`lon`, `lat`),
                point(?, ?)
            ) / 1000 < `range`
        ', [
            $investment->long,
            $investment->lat
        ])->get();

wizjo left a reply on Get Companies In Range From User

@Helmchen: Thank you very much. I feel Im very close to solution, but still something is a bit wrong.

I want to get companies in range 50 km from investment and my query looks like this:

        $companies = Company::whereRaw('
            ST_Distance_Sphere(
                point(`lon`, `lat`),
                point(?, ?)
            ) / 1000 < 50
        ', [
            $investment->lon,
            $investment->long
        ])->get();

...but it returns empty collection. In my database (for testing purposes) I set the same coordinates for investment and one of the companies, so always at least one result should be retrieved.

18 May
1 year ago

wizjo left a reply on Authentication - Logs In At The Second Time

It was not there before. I added this just after observing the problem because I thought I could make sure that user is logged in. So this line is not the problem for sure.

17 May
1 year ago

wizjo started a new conversation Authentication

In my system I have two diffrent types of users: admin and investors. After successfull login each one of them is redirected to the right web area.

However I noticed strange problem. When I log out from one type of account and try to log to the other type at first time Im not logged in- always at second attempt. But, if I try to login to the same account from which I logged out a moment ago, the system logs me in without a problem at the first time.

Here is my authenticate() method from Auth\LoginController.php

    public function authenticate(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        
        if (!$user) {
            Session::flash('error', 'Podano nieprawidłowe dane logowania.');
            return Redirect::to('/')->withInput();          
        }
        
        if (!$user->active) {
            if (!$user->confirmation_code) {
                Session::flash('error', 'Twoje konto zostało zawieszone i do czasu odwieszenia nie możesz zalogować się do systemu.');              
            } else {
                Session::flash('error', 'Twoje konto nie zostało jeszcze aktywowane. Kliknij w link aktywacyjny, który wysłaliśmy na Twój adres e-mail.');
            }           
        }       
        
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1], true)) {
            $user = Auth::loginUsingId($user->id, true);

            if ($user->type == 'admin') {
                return Redirect::to('admin/admins');
            }
            
            return Redirect::to('edycja-danych');
        }

        Session::flash('error', 'Podano nieprawidłowe dane logowania.');
        return Redirect::to('/')->withInput();              
    }
10 May
1 year ago

wizjo left a reply on Session Loging Out

@jlrdw: I meant after visiting several subpages

wizjo left a reply on Session Loging Out

I do it this way, but after a few refreshes I'm still logged out.

Here is my authenticate method:

    public function authenticate(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        
        if (!$user) {
            Session::flash('error', 'Podano nieprawidłowe dane logowania.');
            return Redirect::to('/')->withInput();          
        }
        
        if (!$user->active) {
            if (!$user->confirmation_code) {
                Session::flash('error', 'Twoje konto zostało zawieszone i do czasu odwieszenia nie możesz zalogować się do systemu.');              
            } else {
                Session::flash('error', 'Twoje konto nie zostało jeszcze aktywowane. Kliknij w link aktywacyjny, który wysłaliśmy na Twój adres e-mail.');
            }           
        }       
        
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1], true)) {
            if ($user->type == 'admin') {
                return Redirect::to('admin/admins');
            }
            
            return Redirect::intended();
        }

        Session::flash('error', 'Podano nieprawidłowe dane logowania.');
        return Redirect::to('/')->withInput();              
    }