vincej

vincej

Member Since 6 Years Ago

Calgary, Canada

Experience Points
44,950
Total
Experience

50 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
188
Lessons
Completed
Best Reply Awards
2
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 9
44,950 XP
Jul
07
1 week ago
Activity icon

Replied to How To Clear Cache After Logout

@snapey Many Thanks! It's working as required!

@nakov I checked my middleware, and fixed a few which were not set correctly. Yes, I have multiple guards for admins and contractors, and so I do user auth:admin and auth:contractor

I have been rebuilding my authentication system for two different user types, "Admin" and "Contractor". After making these adjustments things are working as I want it. However, I am very concerned that I do not why it works. I have checked SO, watched Jeffrey's tutorial on Authentication and read some pieces in Matt Stauffer's book. None of these resouces give a clear and articulate description of how all the pieces work together.

How does a level 50 person get to where they are withou clear resources? Do you spend sleepless nights studying the API?? For me, the API is in itself an incomprehensable document. All advice is welcome! :o)

Many thanks !

Jul
04
1 week ago
Activity icon

Started a new Conversation How To Clear Cache After Logout

I tried using this code. However, it does not work. Even after a logout I can use the back button to see the previous pages prior to logout and I can even still interact with the server. However, my session data ie Name and ID, has been cleared. What am I doing wrong?

Many thanks !

public function logout(Request $request)
    {       Auth::guard('web')->logout();
            header("cache-Control:no-store,no-cache, must-revalidate");
            header("cache-Control:post-check=0,pre-check=0",false);
            header("Pragma:no-cache");
            header("Expires: Sat,26 Jul 1997 05:00:00: GMT");
            $request->session()->flush();
            $request->session()->regenerate();
            return redirect()->route('loggedOut');
    }

Jun
16
4 weeks ago
Activity icon

Replied to Place Holder Text Does Not Show In Text Area

Unbelievable! Thank you very much !!

Activity icon

Started a new Conversation Place Holder Text Does Not Show In Text Area

This is bizaar. I use placeholder text in forms to helpthe user how & what to input. Placeholders work fine one simple input fields, however, on a textarea the placeholder text just does not want to show up. Well, not at least untill you have entered something. Then and only then, f you delete the text you have entered does the placehold text show up.

I have tried with Collective as well as with raw HTML. Both gives the same result.

Any ideas?

<div class="form-row form-group">
                    <div class="col-sm-12 col-md-12"><textarea class="form-control" id="quote_comment" placeholder="free format comment" rows="3" name="comment" cols="50"> </textarea></div>
                     </div>
Jun
08
1 month ago
Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

IT WORKED!!! SOLVED!!! MANY THANKS !!!

Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

mysql> SELECT @@sql_mode; +------------------------------------------------------------------------------------------------------------------------+ | @@sql_mode | +------------------------------------------------------------------------------------------------------------------------+ | STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION | +------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)

Jun
07
1 month ago
Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

@guybrush_threepwood Ok, did as you suggested. As works as before. Still with the MySQL error. Is this supposed to help with setting the only_fully_group_by problem?

Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

@guybrush_threepwood Ok, however, I am using Homestead for this deployment. I'm not too sure what url I should use for HOmestead.

Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

@jlrdw Thanks for that. What is curious to me is that my Linux dev machine has the same MySQL version, although it is rinning L6.x.

The article I quoted above required a whole sale massive rewrite, This is very undesirable. Moderate rewrite is not a problem.

Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

@jlrdw Like I said, I have alerady changed the connection to false.

@guybrush_threepwood I'm using L7.11.0

<?php

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('127.0.0.1'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '33060'),
            'database' => env('DB_DATABASE', ''),
            'username' => env('DB_USERNAME', ''),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
            'schema' => 'public',
            'sslmode' => 'prefer',
        ],

        'sqlsrv' => [
            'driver' => 'sqlsrv',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '1433'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'prefix_indexes' => true,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer body of commands than a typical key-value system
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

];


Activity icon

Replied to How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

@jlrdw Brilliant! It works! But here is the bigger question, how can I set this globally? Adding this statement to all my queries is not too bad, however, it seems a little unneccessary.

I have already set config.database.mysql.strict = false to no effect.

Additionally I tried some advice on SO, to set mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); also to no effect.

Activity icon

Started a new Conversation How To Solve The MySQL 5.7.30 "sql_mode=only_full_group_by" Problem

I did a fresh install of Homestead which includes MySQL 5.7.30. I brought across all my Laravel files from my Linux system which also runs MySQL 5.7.30.

For some reason bizaar reason when I run queries on the Homestead system I get the problem:

Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'contraxiq.orders.quote_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Ok - so inside the Homestead version I set the config/database mysql strictsettings to "false". I have also tried turning off the error with no effect.

mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

I have dozens of queries with groupby. As an example, here is one which generates the error:

 public function open_orders() {
        return DB::table('orders')
            ->join('customers', 'customers.id', '=', 'orders.customer_id')
            ->select('orders.reference', 'quote_name','start_date', 'company_name', 'customers.firstname1', 'customers.lastname1', 'customers.city', 'orders.total', 'orders.created_at')
            ->where('orders.status', '=', 'open')
            ->groupBy('orders.reference')
            ->orderBy('orders.created_at')
            ->get();
    }


Wat do I do to fox this problem ? I do not want to rewrite all the dozens of queries as suggested by this post: https://gabi.dev/2016/03/03/group-by-are-you-sure-you-know-it/

Many Thanks !!

May
20
1 month ago
Activity icon

Started a new Conversation Multi-Auth Is Not Working With, "protected $redirectTo = RouteServiceProvider::HOME;"

When I click "log out" it goes to the $redirectTo, and entirely ignores my log out code.

For some reason, I can log into my two different user dashboards, but when I want to log out, this stupid constant keeps wanting to take me to "Home" which by default is "login". All I want to do is log out my user! Nothing else. Commenting the Const does not help, you just get an error.

What am I am I doing wrong?

This is my controller code:


    public function userlogout(Request $request)
    {
            Auth::guard('web')->logout();
            $request->session()->flush();
            $request->session()->regenerate();
            return redirect()->route('logged_out');
    }

May
12
2 months ago
Activity icon

Replied to Upgraded To L7 Now Getting Error: "InvalidArgumentException Auth Guard [admin] Is Not Defined."

Given that the multi auth system I borrowed from John Curtis / DevMarketer stems from L5, and now we have a L7 / UI, I have made the decision to make use of the UI system. So I am reinstalling Homestead with a fresh copy of L7. I will add the UI and then build things back up from there. I have found a new tut for multi-auth aimed at L7 and so I'll try that.

I'm sure I'll update this Q. tomorrow perhaps when it all goes to rat shit. :o)

Many thanks for all your contributions.

Activity icon

Replied to Upgraded To L7 Now Getting Error: "InvalidArgumentException Auth Guard [admin] Is Not Defined."

The back ground is, that back with L5 I built a multi-authentication system allowing users and admins using a tutorial from "devMarketer" aka John Curtis. Laravel could not support multiple users, and still can't (??) Can laravel / ui support multiple user types??

Activity icon

Started a new Conversation Upgraded To L7 Now Getting Error: "InvalidArgumentException Auth Guard [admin] Is Not Defined."

Everthing works on L6 Linux server. Now I have moved my app over to Windows 10, Homestead with L7 using a copy and paste. I get my login screen, however, when I try to login I am getting:

InvalidArgumentException
Auth guard [admin] is not defined.

I have checked and my Handler file has the guard there as too the RedirectifAuthenticated middleware also the auth.php.

I have not used the laravel/ui

Any ideas where I should start looking or why this is failing under L7?

May
11
2 months ago
Activity icon

Replied to Homestead: Imported Site Will Not Display

Well, I managed to get a nice login screen! Yeah! So something is working now. However, I now get a new error on my first page inside my app:

InvalidArgumentException
Auth guard [admin] is not defined.

Every single controller uses Auth guard [admin]. So I guess all that is gone. Back in L5 days I built a dual athentication system for admins and for users. Do I need to rebuild all that ?

Activity icon

Replied to Homestead: Imported Site Will Not Display

Ok - I found the advice re the authentication scafolding.

Activity icon

Replied to Homestead: Imported Site Will Not Display

Brilliant Thanks guys, it looks like I am now reaching my app however, I have a new problem which appears not to be on the upgrade guide. My login form uses the trait use AuthenticatesUsers; I am getting a not found error. So when I hunt down use Illuminate\Foundation\Auth\AuthenticatesUsers;. Sure enough it is not there anymore. So, where has it gone? Any ideas?? Many Thanks !!

Error:

Symfony\Component\ErrorHandler\Error\FatalError
Trait 'Illuminate\Foundation\Auth\AuthenticatesUsers' not found

Activity icon

Replied to Homestead: Imported Site Will Not Display

I'm not really sure what to do with this. I have had a look at the L7 upgrade guide on the topic of Symphony 5 Related Upgrades. What am I supposed to do with these code changes?? My current except file looks like this:

<?php

namespace App\Exceptions;


use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

       
    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }


    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        $guard = array_get($exception->guards(), 0);

        switch ($guard) {
                case 'admin':
                $login =  'admin.login';
                break;


            default:
                $login = 'portalLoginForm';
                break;
        }

        return redirect()->guest(route($login));
    }
}


Activity icon

Replied to Homestead: Imported Site Will Not Display

Ok - looks like the problem has something to do with upgrading from L6 to L7.

https://github.com/laravel/framework/issues/31686

Activity icon

Replied to Homestead: Imported Site Will Not Display

Ok - I found where artisan is, and cd'ed into the laravel project called test where aritsan is. I got a big error when calling php artisan . Hopefully this might help diagnose the problem - Many thanks !!

[email protected]:~/code/test$ php artisan
PHP Fatal error:  Declaration of App\Exceptions\Handler::report(Exception $exception) must be compatible with Illuminate\Foundation\Exceptions\Handler::report(Throwable $e) in /home/vagrant/code/test/app/Exceptions/Handler.php on line 33
PHP Fatal error:  Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php:805
Stack trace:
#0 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): ReflectionClass->__construct()
#1 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php(687): Illuminate\Container\Container->build()
#2 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(796): Illuminate\Container\Container->resolve()
#3 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php(265): Illuminate\Foundation\Application->resolve()
#4 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php(801): Illuminate\Container\Container->Illuminate\Container\{closure}()
#5 /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php(687): Illuminate\Container\Container->bu in /home/vagrant/code/test/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 807



Activity icon

Replied to Homestead: Imported Site Will Not Display

oops - that's "cache" not car wash. Voice to text get's confused!

Activity icon

Replied to Homestead: Imported Site Will Not Display

Yes I set up a project it is called my app..test. I'm not sure how I could clear my route cache if I can't get into PHP artisan. I copied files over rather than organically creating them.

Activity icon

Replied to Homestead: Imported Site Will Not Display

Thanks for that can you please tell me where the art is an file is supposed to be ?

Activity icon

Started a new Conversation Homestead: Imported Site Will Not Display

I have loaded homestead and Laravel 7 onto Windows 10. The Laravel Homepage displays nicely. OK, so I have then copied and pasted my establsihed and working code ( App, Resources, Public, Routes) from my LInux server, into my Win10 users\vince\code folder which should update the Homestead server. Sure enough it is in the Code folder in Homestead. Great.

Excepting for the Laravel Welcome page, nothing from my application displays in the browser when I use the url for the Homestead site. All I get is an error This page isn't working, mysite.test is currently inavailable to handel this request, error 500.

Ok, so I provisioned the site again. I have halted Vagrant and restarted. Neither helped. However, still, the Laravel Welcome page shows and I can change it.

I tried to use php artisan to try to clear the cache on the Homestead site, however, I get:

[email protected]:~$ php artisan
Could not open input file: artisan

I did see a post on Laracasts saying some guy added Way/generators and claims that fixed his problem, but that makes zero sense to me as that package just generates modesl and controllers.

So any / all advise is welcome.

Many Thanks !

Apr
26
2 months ago
Activity icon

Awarded Best Reply on Vagrant Does Not Boot Into Homestead

SOLVED! Ok, as often is the case, I made a dumb mistake.

Because I have previously been implimenting PHP environments on my Windows 10 laptop, I had designated in my Hosts file 127.0.0.1 localhost. So, when I entered the IP for my Homestead app as 192.168.10.10 Vagrant was grabing the local host IP rather than the Vagrant app IP. So it did not boot into Homestead but rather into Vagrant itself.

So - for the benefit of anyone else wanting to install Homestead on Windows 10, I have found that there is only 1 explanation out there, which is succinct and clear. Trust me, I tried them all! Credit to this guy on youtube:

Peter Steel ( https://www.youtube.com/watch?v=Il08--droNI )

Activity icon

Replied to Vagrant Does Not Boot Into Homestead

SOLVED! Ok, as often is the case, I made a dumb mistake.

Because I have previously been implimenting PHP environments on my Windows 10 laptop, I had designated in my Hosts file 127.0.0.1 localhost. So, when I entered the IP for my Homestead app as 192.168.10.10 Vagrant was grabing the local host IP rather than the Vagrant app IP. So it did not boot into Homestead but rather into Vagrant itself.

So - for the benefit of anyone else wanting to install Homestead on Windows 10, I have found that there is only 1 explanation out there, which is succinct and clear. Trust me, I tried them all! Credit to this guy on youtube:

Peter Steel ( https://www.youtube.com/watch?v=Il08--droNI )

Apr
25
2 months ago
Activity icon

Started a new Conversation Vagrant Does Not Boot Into Homestead

I'm new to Homestead. I'm deploying Homestead on Windows 10.

Everything appears to be installed correctly. When I do a "Vagrant up" I get the nice "HOMESTEAD" banner showing in Git Bash. however, the command line shows [email protected] rather than [email protected]. Furthermore, if I do an ls there is no Code folder.

I have tried deleting the Vagrantfile and doing a fresh init. Also I did vagrant provision -- force. I even have removed Vagrant and reinstalled it.

What have I done wrong, and how do I fix it?

Many thanks

Apr
18
2 months ago
Activity icon

Replied to How To Best Format Data For Use In JqTree

I forced myself into reading about Eleoquent relationships. Relationships require the use of 2 or more tables. My categories are held on a single table. columns are: category_id (prime), parent_id, name, rgt, lft, depth.

I imagine that is why relationships won't work for me. Ugh. Thanks

Apr
17
2 months ago
Activity icon

Replied to How To Best Format Data For Use In JqTree

@nolros Thanks for the help. I only use nested sets. And I only use raw SQL, as I am old school. I tried reading through the Laravel Docs on Eloquent this pm and after 5 minutes decided who ever writes these docs are masters at making the simple extremely complicated. I'm not sure my brain can handle the whole song and dance on Eloquent. I don't know why this is supposed to be easier that SQL. For me it is much harder.

Anyway, I tried your suggestion. I had to make some adjustments to reflect the name of my model. Sadly, whilst it executed, I didn't get anything out of it. Is this perhaps because both my parent_id and category_id are in the same table and hasmany assumes they are in difference tables? this is what I got out:

Illuminate\Database\Eloquent\Relations\HasMany {#439 ▼
  #foreignKey: "categories.parent_id"
  #localKey: "category_id"
  #query: Illuminate\Database\Eloquent\Builder {#575 ▶}
  #parent: App\Models\Category {#536 ▼
    #table: "categories"
    #primaryKey: "category_id"
    #guarded: array:1 [▶]
    +timestamps: true
    #hidden: array:3 [▶]
    #with: array:1 [▶]
    #connection: null
    #keyType: "int"
    +incrementing: true
    #withCount: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    #visible: []
    #fillable: []
  }
  #related: App\Models\Category {#564 ▼
    #table: "categories"
    #primaryKey: "category_id"
    #guarded: array:1 [▶]
    +timestamps: true
    #hidden: array:3 [▶]
    #with: array:1 [▶]
    #connection: null
    #keyType: "int"
    +incrementing: true
    #withCount: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    #visible: []
    #fillable: []
  }
}

Apr
16
2 months ago
Activity icon

Replied to How To Best Format Data For Use In JqTree

Hi Nolros! Haven't seen you for years. I'll give it a try tomorrow. Many thanks !

Activity icon

Replied to How To Best Format Data For Use In JqTree

OK - I have avoided eloquent like Covid-19. And so I am just shooting in the dark here. Guess I had better have a look at it.

Activity icon

Replied to How To Best Format Data For Use In JqTree

I have 4 levels excluding Root. Gave it a try and got:

Call to undefined relationship [children] on model [App\Models\Category].
Activity icon

Started a new Conversation How To Best Format Data For Use In JqTree

jqTree requires the data coming off your controller to be in a specific format:

var data = [
    {
        name: 'node1', id: 1,
        children: [
            { name: 'child1', id: 2 },
            { name: 'child2', id: 3 }
        ]
    },
    {
        name: 'node2', id: 4,
        children: [
            { name: 'child3', id: 5 }
        ]
    }
];


I found on SO some code which works BUT the code does not include the ID of the category. Ugh. I have tried frigging with the Javascript to include the category_id but all I get is errors. So - I have two options, either try to fix the SO code or develop my script to convert my collection to fit jqTree. If someone can point me towards how to fix the SO code, then that would be easiest. If I have to develop my own JS script to reformat my collection, then I have offered the format of my collection below.

Here is the SO code:

var jqTreeData = function (data) {
        var source = [];
        var items = [];
        // build hierarchical source.
        for (i = 0; i < data.length; i++) {
            var item = data[i];
            var title = item["Title"];
            var reportsToId = item["ReportsToId"];
            var id = item["Id"];

            if (items[reportsToId]) {
                var item =
                {
                    label: title
                };

                if (!items[reportsToId].children) {
                    items[reportsToId].children = [];
                }

                items[reportsToId].children[items[reportsToId].children.length] = item;
                items[id] = item;
            }
            else {
                items[id] =
                {
                    label: title
                };

                source[0] = items[id];
            }
        }
        return source;
    }


My data coming off of my controller is in a collection and looks like this:

 1 => App\Models\Category {#660 ▼
     
      #attributes: array:10 [▼
        "category_id" => 53
        "parent_id" => "1"
        "lft" => 10
        "rgt" => 21
        "depth" => 1
        "name" => "Materials"
        "notes" => null
        "status" => "active"
        "created_at" => "2020-04-01 11:48:28"
        "updated_at" => null
      ]

So, somehow, by magic, I have to get my data reformatted into the jqTree structure. Each node of the tree has a parent_id. Each category_id might / maybe also have children.

Many Thanks to all !!

Mar
20
3 months ago
Activity icon

Started a new Conversation Laragon With Xdebug Will Not Work With Laravel

I've been a Linux user for years, but am testing out Laragon on my laptop. Laravel installs fine, however, when I install xdebug according to the XDEBUG instructions, into C:\laragon\bin\php\php-7.2.19-Win32-VC15-x64\ext Laravel can no longer be found in the web page.

When I remove it, all is well again.

Does anyone have any ideas what to do about this?

Many thanks.

Mar
18
3 months ago
Activity icon

Replied to Need Help Converting Complex MySQL Query

Everything is working perfectly. However, can you offer some advice on how I can protect this query from SLQ injection. @willvincent was using some substituions, but I don't seem to be able to make this work .. but then I might be doing things in correctly.

Many thanks !

public function addNode($request)
    {
            DB::unprepared("
            LOCK TABLE categories WRITE;
            SELECT @myLeft := lft FROM categories
            WHERE name =  '$request->parent_category';
            UPDATE categories SET rgt = rgt + 2 WHERE rgt > @myLeft;
            UPDATE categories SET lft = lft + 2 WHERE lft > @myLeft;
            INSERT INTO categories(parent_id, name, lft, rgt, depth) VALUES('$request->category_id', '$request->new_category', @myLeft + 1, @myLeft + 2,'$request->depth' +1); 
            UNLOCK TABLES;");


Mar
12
4 months ago
Activity icon

Replied to Need Help Converting Complex MySQL Query

@willvincent What is a nested_insert ... I see no mention of this on SO or the docs.

Activity icon

Replied to Need Help Converting Complex MySQL Query

Can't believe it, I solved the problem. Yes, I tried the stored procedure route, and again, Laravel did not like the query. BUT, I found something on SO which outlines all the various DB::() functions, including DB::unprepared()

(https://stackoverflow.com/questions/25346162/difference-between-laravels-raw-sql-functions )

Yet, none of this is in the user docs. so - in the end, this works for me. I hope this might one day help someone else.

 public function addNode($category, $value)
    {
            DB::unprepared("
            LOCK TABLE nested_categories WRITE;
            SELECT @myLeft := lft FROM nested_categories
            WHERE name =  '$category';
            UPDATE nested_categories SET rgt = rgt + 2 WHERE rgt > @myLeft;
            UPDATE nested_categories SET lft = lft + 2 WHERE lft > @myLeft;
            INSERT INTO nested_categories(name, lft, rgt) VALUES( '$value', @myLeft + 1, @myLeft + 2); 
            UNLOCK TABLES;");
    }


Mar
10
4 months ago
Activity icon

Replied to Need Help Converting Complex MySQL Query

Good idea ... I'm not getting anywhere with "Parameter Grouping". I'll give it a try. Thanks.

Activity icon

Replied to Need Help Converting Complex MySQL Query

thanks @willvincent It's a mystery. It's a mystery. My sql works fine inside an sql console. Ok, I do not use replacements. I do this:

LOCK TABLES nested_categories WRITE;
SELECT @myRight := rgt FROM nested_categories
WHERE name = 'Root';
UPDATE nested_categories SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_categories SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_categories(name, lft, rgt) VALUES('Materials', @myRight + 1, @myRight + 2);
UNLOCK TABLES;

When I use DB::raw() Laravel just skips right over it and ignores it.

So - I guess, I might try to convert this query into QueryBuilder using the passage in the docs called Parameter Grouping. I'm not very good with QB, hence I prefer raw SQL. Not sure how well this might work This is the only thing I'm not fond of with Laravel, the fact you can not just use raw SQL.

Cheers

Mar
09
4 months ago
Activity icon

Replied to Need Help Converting Complex MySQL Query

@willvincent Hi Thanks for your help. Sorry to hassle you. I applied your fix exactly by copy and paste but I am still getting an error, albeit a different one:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE categories SET rgt = rgt + 2 WHERE rgt > @myRight; ◀
    UPDATE categories ' at line 3 (SQL: SELECT @myRight := rgt FROM categories
    WHERE name = Cedar;
    UPDATE categories SET rgt = rgt + 2 WHERE rgt > @myRight;
    UPDATE categories SET lft = lft + 2 WHERE lft > @myRight;
    INSERT INTO categories(name, lft, rgt) VALUES(Red, @myRight + 1, @myRight + 2))

FYI - $parent equates to Cedar and $node equates to Red.

Any ideas ?

Many thanks !!

Mar
05
4 months ago
Activity icon

Replied to Need Help Converting Complex MySQL Query

@jlrdw to be honest because I don't know how to convert this kind of query into a DB facade, hence my post. I did give it many tries though, and failed miserably.

Activity icon

Started a new Conversation Need Help Converting Complex MySQL Query

I tend to write my complex queries in raw SQL and then try to fit them into Laravel. I'm not succeeding getting the two arguments, $parent and $node into the DB::select. The query works perfectly well inside an SQL console. In a previous post from me I was advised to simply wrap my raw query in DB::select(). additionally I found further advice on Laracasts on how to lock tables, and also here: ( https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html )

Any ideas ??

 public function createCategory($parent, $node) {
     DB::raw('LOCK TABLE categories WRITE');
     DB::select(
       'SELECT @myRight := rgt FROM categories
        WHERE name = $parent;                                     // $parent value not available 
        UPDATE categories SET rgt = rgt + 2 WHERE rgt > @myRight;
        UPDATE categories SET lft = lft + 2 WHERE lft > @myRight;
        INSERT INTO categories(name, lft, rgt) VALUES($node, @myRight + 1, @myRight + 2)');   // $node value not available
        DB::raw('UNLOCK TABLES');
         }

Mar
02
4 months ago
Activity icon

Started a new Conversation Getting Error: Call To A Member Function AppendNode() On String

I'm not sure how to deal with this error. SO is not very enlightening. I am using the Nested Set package from Kalnoy (https://github.com/lazychaser/laravel-nestedset#inserting-nodes)

In am inserting a new node as given 1/3 way down his page.

Here he offers several ways to achieve the result.

Things do work when I do this:

Category::create(
             ['category_name'=>$request['new_category'],
             'id'=> $request['parent_category']]);

But when I do this, the other examples give me the same error. By way of example, I am applying the following.

 $request['parent_category']->appendNode($request['new_category']);

I'm not sure how to make this work, any suggestions?

Feb
14
5 months ago
Activity icon

Replied to Need Advice On A Collection

I should have mentioned that the various queries pull data using QueryBuilder and it gives me arrays, and or collections. I guess I could convert to objects, but I have no experience in doing that and frankly it was a pain to look it up, digest it, and use it. I see no Laravel helper for this, so I just took the easy road. Cheers !

Activity icon

Replied to Need Advice On A Collection

@snapey @jlrdw I'm not going to pretend that I have a good answer to your questions, Here is the function sitting in my model, it serves two separate controllers.

 public function workorder_contents($id){

        $contractors = $this->contractors();//this finds all contractor names with their id's and puts them into a select box*/
        $workorder = WorkOrder::where('order_number','=',$id)->get(); //this finds costs and margins from the created work order.
        $selected_contractor = $this->selected_contractor($id); // this finds the established and selected contractor for this job
        $sales_order= app('App\Models\Order')->salesorder_partialsearch($workorder[0]['order_number']); // this finds all the products which were orginally ordered as a sales order.
        $product_margin = app('App\Models\Order')->product_margin($id);

        $margin = 0;
        $gross_margin = 0;
        $total_cost = 0;

        // this calculates the total gross margin from the sales order.
        foreach ($sales_order as $so){
            $discounted_cost = $so->line_cost * ((100-$so->discount) / 100);
            $cost_quantity =  ($so->cost_price * $so->quantity );
            $margin =  $discounted_cost - $cost_quantity;

            $total_cost += $cost_quantity;
            $gross_margin += $margin;
            number_format($gross_margin,2);
        }

        $total_cost = $total_cost + $workorder[0]['extras_total'];

        return array('contractors'=>$contractors, 'workorder'=>$workorder,'selected_contractor'=>$selected_contractor,'sales_order'=>$sales_order,'gross_margin'=>$gross_margin,'total_cost'=>$total_cost);

    }

Activity icon

Replied to Need Advice On A Collection

Thank you all ! I knew it would be easy, but not that easy! I have a little supplementary question for my academic curiosity.

I only gave you the one array, but in fact I am passing about 7, which in turn have loads of values.

so I have this:

 $data = $this->workorder_contents($id);

return View('workorders',  compact('data') )

all good. But when it gets to my view I have to do this:

$data['workorder'][0]['wo_address'])

$data['sales_order'][0]['product_name']

etc, etc  for every single array and value in my view of which there are many. It works though. 

Question : is there a cleaner way of achieving the same outcome or is this the best there is??

Many thanks !!

Feb
13
5 months ago
Activity icon

Started a new Conversation Need Advice On A Collection

Problem: I am trying to get values from a collection returned to a view. Sort of like this:

return View('workorders', compact( 'values['workorder'] ));

Sounds easy? I'm not getting there. Any suggestions ?? It should be easy.

Background Details I have a function in a controller which generates several values. I return them to another controller as an array. In turn, the other controller will dispatch them to a view. This is what I have got so far:

My Array

 return array('contractors'=>$contractors,'workorder'=>$workorder,'selected_contractor'=>$selected_contractor,'sales_order'=>$sales_order,'gross_margin'=>$gross_margin,'total_cost'=>$total_cost);

Received in the second function

$values = $this->workorder_contents($id);

Alls well so far. If I do a dd($values['workorder']); I get a nice collection out which looks like this:

Illuminate\Database\Eloquent\Collection {#819 ▼
  #items: array:1 [▼
    0 => App\Models\WorkOrder {#820 ▼
      #table: "workorders"
      #primaryKey: "id"
      #guarded: array:1 [▶]
      +timestamps: true
      #hidden: array:2 [▶]
      #dates: array:2 [▶]
      #connection: "mysql"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:28 [▼
        "id" => 8
        "contractor_id" => 67
        "order_number" => "Tru161219-53"
        "accepted" => null
        "start_date" => "Thu Feb 20, 2020"
        "wo_address" => "151 Alandale Place Calgary T3Z3L9"
        "contact" => "Donald Trump"
        "crew" => null
        "rate" => "56"
        "product" => null
        "colour" => null
        "uplift" => "12"
        "attribute" => null
        "material_qty" => 10
        "work" => "install"
        "extras" => null
        "gross_margin" => "2"
        "margin_percent" => "28"
        "project_costs" => "5390.00"
        "extras_total" => "1230.00"
        "contract" => "0.00"
        "total_contractor" => "1790.00"
        "status" => "open"
        "closed_at" => null
        "wo_comment" => null
        "created_at" => "2020-02-12 15:48:02"
        "updated_at" => "2020-02-12 15:48:02"
        "deleted_at" => null
      ]
      #original: array:28 [▶]
      #changes: []


Jan
13
6 months ago
Activity icon

Started a new Conversation Managing Multiple Ajax Calls On Single Page View

I am building a Dashboard using Google Charts. All straight forward, except that each chart represents a different data set out of my DB. So, is there a clever way of avoiding a separate Ajax call for each Google chart? Also, any thoughts on how best to fire multiple Ajax calls when the page opens to avoid all kinds of conflicts?

Many Thanks !