ludo1960

ludo1960

Member Since 2 Months Ago

Experience Points 1,220
Experience
Level
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

14 Jan
6 days ago

ludo1960 left a reply on Add Array=>value To Multi Dimensional Key Function

And the answer is:

function FlattenMultiArray($array,$bKeepKeys=true,$key_prefix='')
{
    
    $array_flattened=Array();
    foreach($array as $key=>$value){

        if(Is_Array($value)){
            $array_flattened=Array_Merge(
                $array_flattened,
                FlattenMultiArray($value,$bKeepKeys,$key)
            );
        }
        else{
            if($bKeepKeys){
                $array_flattened["{$key_prefix}{$key}"]=$value;
            }
            else{
                $array_flattened[]=$value;
            }
        }
    }

    return $array_flattened;
}

Usage:

$resp = FlattenMultiArray($whateverarray, true);

print_r(resp); //print out the lot

print_r(array_keys($resp)); //print out the keys only

print_r($resp['whatevermykey']); //print out any key value

enjoy :)

13 Jan
1 week ago

ludo1960 left a reply on Add Array=>value To Multi Dimensional Key Function

I have a multi dimensional array that I need to extract specific key value pairs from. Having tried numerous crawler/flatten functions, the only function that i've come across that successfully crawls the array is the one I posted above. I have not tried laravel flatten but i did try https://davidwalsh.name/flatten-nested-arrays-php and it did not crawl the array.

function array_keys_multi(array $array)
{
    $keys = array();

    foreach ($array as $key => $value) {
        $keys[] = $key;
        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key])); // Key value to be added here
        }
    }
    return $keys;
}

Is that clear enough?

ludo1960 left a reply on Add Array=>value To Multi Dimensional Key Function

The function I posted successfully crawls a multi dimensional array and returns the Key but not the associated value. I don't see how your solution adds the value to the key in the function above. "And what is a key function" I have no idea? Where did that come from??

ludo1960 started a new conversation Add Array=>value To Multi Dimensional Key Function

Hi guys, I've tried lots and lots of so called solutions to my issue e.g. https://davidwalsh.name/flatten-nested-arrays-php and https://stackoverflow.com/questions/38089479/get-all-values-from-multidimensional-array but the only solution that successfully crawls the given array is the function below. Only problem is that only returns the array keys and not the array values:.

function array_keys_multi(array $array)
{
    $keys = array();
    foreach ($array as $key => $value) {
        $keys[] = $key;
        if (is_array($array[$key])) {
            $keys = array_merge($keys, array_keys_multi($array[$key]));
            "<br>";
        }
    }
    return $keys;
}

How can I add the array=>value to the above function?

11 Jan
1 week ago

ludo1960 left a reply on Convert JSON String To Array

The only other thing is how to adjust the function so the output simulates the array structure ie a after every sub array? Any ideas?

ludo1960 left a reply on Convert JSON String To Array

yeah I figured that out, and it works a treat, All keys and values are returned, thanks guys!

ludo1960 left a reply on Convert JSON String To Array

I thought that was what the function returned? If not what does it return?

ludo1960 left a reply on Convert JSON String To Array

ok tried that:

$response = json_decode(file_get_contents($url), true);

array_keys_multi($response);

print_r($keys);

but nothing is returned, am I doing it right?

ludo1960 left a reply on Convert JSON String To Array

found this little beauty:

function array_keys_multi(array $array)
{
    $keys = array();
    foreach ($response as $key => $value) {
        $keys[] = $key;
        if (is_array($response[$key])) {
            $keys = array_merge($keys, array_keys_multi($response[$key]));
        }
    }
    return $keys;
}

but how to use it in my case: ie how to call the function?

ludo1960 left a reply on Convert JSON String To Array

How do I find all the Key names in a nested Array? $keys = array_keys($response) only returns the keys from Array[0]

ludo1960 left a reply on Convert JSON String To Array

That's fine for items in Array[0] but what about the other nested Arrays? Is there a PHP command to navigate a tree structure of Arrays?

ludo1960 left a reply on Convert JSON String To Array

ok so:

$response = json_decode(file_get_contents($url), true);

print_r(array_keys($response));

gives:

Array ( [0] => country [1] => result_count [2] => longitude [3] => area_name [4] => listing [5] => street [6] => town [7] => latitude [8] => county [9] => bounding_box [10] => postcode )

print_r($response) ;
gives:

Array ( [country] => England [result_count] => 1796 [longitude] => -1.210158 [area_name] => Oxford [listing] => Array ( [0] => Array ( [country_code] => gb [num_floors] => 0 [image_150_113_url] => https://lid.zoocdn.com/150/113/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [listing_status] => sale [num_bedrooms] => 6 [location_is_approximate] => 0 [image_50_38_url] => https://lid.zoocdn.com/50/38/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [latitude] => 51.74293 [furnished_state] => [agent_address] => High Street, Goring, Reading [category] => Residential [property_type] => Detached house [longitude] => -1.313658 [thumbnail_url] => https://lid.zoocdn.com/80/60/d23e28cf074d77c62ec7151dab09cffa8dbaf210.jpg [description] => Nestled in a private corner of exclusive Hid’s Copse Road on the outskirts of Oxford, Water Combe is a brand new property constructed to an extraordinarily high standard with an astonishing attention to detail. The property is full of light and space with most rooms having a double aspect and large windows designed to take advantage of the far reaching and garden views. Bespoke features include a luxurious designer kitchen/breakfast room, generous reception rooms, spacious hallways and landings, an internal green oak frame which adds stunning character, wide oak floors, large bedrooms and fabulous bathrooms with Bateau bath tubs.Set within 1.2 acres, the landscaping has been designed around the Fairy Glen at the bottom of the garden and the Fairy theme continues throughout the house and garden. This enchanting home has had no expense spared to create a unique home for the discerning buyer. Awaiting EPC Rating.Local informationCumnor Hill is a sought after residential area just 1.5 miles from the centre of Oxford. It is well served by communications with access to the A34 and Oxford ring road, connecting to the M4 and M40 motorways, with the regional centres of Newbury and Swindon also within easy reach.Communications by rail are also excellent with fast trains from either Oxford or Didcot to London Paddington taking about 50 and 45 minutes respectively. From the coach station at Gloucester Green there are regular services to London Heathrow and Gatwick airports.Hid’s Copse

ludo1960 left a reply on Convert JSON String To Array

Very quick answer, Array[0] is returned but there are more nested Arrays, how to access those?

ludo1960 started a new conversation Convert JSON String To Array

Hi guys,

Consider the following:

$url = "https://someURI";

$response = json_decode(file_get_contents($url));

print_r($response) ;  //nice big string returned 

print_r (explode(" => ",$response)); //nothing returned ???

How do I deal with a big string, can I convert it to an array? Data is structured so:

stdClass Object ( [country] => England [result_count] => 1797 [longitude] => -1.210158 [area_name] => Oxford [listing] => Array ( [0] => stdClass Object ( [country_code] => gb [num_floors] => 0 [image_150_113_url] => https://some.jpg[listing_status] => sale [num_bedrooms] => 6 [location_is_approximate] => 0 [image_50_38_url] => https://another.jpg [latitude] => 51.74293 [furnished_state] => [agent_address] => High Street, Goring, Reading [category] => Residential [property_type] => Detached house [longitude] => -1.313658 [thumbnail_url] => blah blah

If it was an array I could get the keys to see what i'm dealing with, any idea guys?

03 Jan
2 weeks ago

ludo1960 left a reply on CSS Advice

@REALRANDYALLEN - Alas the result is still the buttons are stacked! I changed '''

Operations to Operation Buttons '''

And it worked! A ghastly hack I know, but serves me right for skipping CSS school! Any other gems out there?

ludo1960 started a new conversation CSS Advice

Happy new year all!

Got a small css problem:

<div class="col-lg-10 col-lg-offset-1">
    <h1><i class="fa fa-users"></i> User Administration <a href="{{ route('roles.index') }}" class="btn btn-default pull-right">Roles</a>
    <a href="{{ route('permissions.index') }}" class="btn btn-default pull-right">Permissions</a></h1>
    <hr>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">

            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Date/Time Added</th>
                    <th>User Roles</th>
                    <th>Operations</th>
                </tr>
            </thead>

            <tbody>
                @foreach ($users as $user)
                <tr>

                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                    <td>{{ $user->created_at->format('F d, Y h:ia') }}</td>
                    <td>{{  $user->roles()->pluck('name')->implode(' ') }}</td>{{-- Retrieve array of roles associated to a user and convert to string --}}
                    <td>
                    <a href="{{ route('users.edit', $user->id) }}" class="btn btn-info pull-left" style="margin-right: 3px;">Edit</a>

                    {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!}
                    {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
                    {!! Form::close() !!}

                    </td>
                </tr>
                @endforeach
            </tbody>

        </table>
    </div>

I've tried playing around with it, but not being a CSS buff, i'm pretty much going round in circles. The EDIT and DELETE button appear stacked on top of one another, naturally I would like the buttons to appear side by side, any ideas guys?

21 Dec
4 weeks ago

ludo1960 left a reply on Instantiate Abstract Class

hmm, why the PHP_EOL ? is that another gotcha?

ludo1960 left a reply on Instantiate Abstract Class

as the great professor Frankenstein once said "it lives" Thanks guys, now time to get myself stuck in endless loops!

ludo1960 left a reply on Instantiate Abstract Class

ok done that, now it can't find DOMDocument? where does that little blighter live?

ludo1960 left a reply on Instantiate Abstract Class

What is the same thing?

<?php



namespace App\Console\Commands;

use Illuminate\Console\Command;

use \Spatie\Crawler\CrawlObserver;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;


class MyPages extends CrawlObserver{

If this is wrong what is the right answer?

ludo1960 left a reply on Instantiate Abstract Class

Changed the top to:

namespace App\Console\Commands;

use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;

use Illuminate\Console\Command;

use \Spatie\Crawler\CrawlObserver; ....

Now the error is :

 php artisan crawler:crawl

   Symfony\Component\Debug\Exception\FatalThrowableError  : Class 'App\Console\Commands\Crawler\Crawler' not found

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:73
    69| 
    70|     public function handle()
    71|     {
    72|         // Add your code here
  > 73|         Crawler\Crawler::create()
    74|         ->setCrawlObserver(new MyPages())
    75|         ->setMaximumCrawlCount(1)
    76|         ->ignoreRobots() //github doesnt like scrapers...
    77|         ->startCrawling('http://php.local.com');

  Exception trace:

  1   App\Console\Commands\CrawlerCommand::handle()
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

  2   call_user_func_array([])
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

  Please use the argument -v to see more details.
[email protected]:/var/www/test.local.com$ 
[email protected]:/var/www/test.local.com$ php artisan crawler:crawl

   Symfony\Component\Debug\Exception\FatalThrowableError  : Class 'App\Console\Commands\Crawler\Crawler' not found

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:75
    71| 
    72|     public function handle()
    73|     {
    74|         // Add your code here
  > 75|         Crawler\Crawler::create()
    76|         ->setCrawlObserver(new MyPages())
    77|         ->setMaximumCrawlCount(1)
    78|         ->ignoreRobots() //github doesnt like scrapers...
    79|         ->startCrawling('http://php.local.com');

  Exception trace:

  1   App\Console\Commands\CrawlerCommand::handle()
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

  2   call_user_func_array([])
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

Hope Santa can help.....

ludo1960 left a reply on Instantiate Abstract Class

Still no joy, eeek!!!

complete code:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use \Spatie\Crawler\CrawlObserver;

class MyPages extends CrawlObserver{

    private $pages =[];


    public function crawled(
        UriInterface $url,
        ResponseInterface $response,
        ?UriInterface $foundOnUrl = null
    )
    {

        $path = $url->getPath();
        $doc = new DOMDocument();
        @$doc->loadHTML($response->getBody());
        $title = $doc->getElementsByTagName("title")[0]->nodeValue;

        $this->pages[] = [
            'path'=>$path,
            'title'=> $title
        ];
    }

    public function crawlFailed(
        UriInterface $url,
        RequestException $requestException,
        ?UriInterface $foundOnUrl = null
    )
    {
        echo 'failed';
    }

    public function finishedCrawling()
    {
        echo 'crawled ' . count($this->pages) . ' urls' . PHP_EOL;
        foreach ($this->pages as $page){
            echo sprintf("Url  path: %s Page title: %s%s", $page['path'], $page['title'], PHP_EOL);
        }
    }

}


class CrawlerCommand extends Command
{

    protected $signature = 'crawler:crawl';

    protected $description = 'Crawl a Website';


    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        // Add your code here
        Crawler\Crawler::create()
        ->setCrawlObserver(new MyPages())
        ->setMaximumCrawlCount(1)
        ->ignoreRobots() //github doesnt like scrapers...
        ->startCrawling('http://php.local.com');
    }
}

Error returned:

php artisan crawler:crawl
PHP Fatal error:  Declaration of App\Console\Commands\MyPages::crawled(App\Console\Commands\UriInterface $url, App\Console\Commands\ResponseInterface $response, ?App\Console\Commands\UriInterface $foundOnUrl = NULL) must be compatible with Spatie\Crawler\CrawlObserver::crawled(Psr\Http\Message\UriInterface $url, Psr\Http\Message\ResponseInterface $response, ?Psr\Http\Message\UriInterface $foundOnUrl = NULL) in /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php on line 9

   Symfony\Component\Debug\Exception\FatalErrorException  : Declaration of App\Console\Commands\MyPages::crawled(App\Console\Commands\UriInterface $url, App\Console\Commands\ResponseInterface $response, ?App\Console\Commands\UriInterface $foundOnUrl = NULL) must be compatible with Spatie\Crawler\CrawlObserver::crawled(Psr\Http\Message\UriInterface $url, Psr\Http\Message\ResponseInterface $response, ?Psr\Http\Message\UriInterface $foundOnUrl = NULL)

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:9
     5| use Illuminate\Console\Command;
     6| 
     7| use \Spatie\Crawler\CrawlObserver;
     8| 
  >  9| class MyPages extends CrawlObserver{
    10| 
    11|     private $pages =[];
    12| 
    13| 


   Whoops\Exception\ErrorException  : Declaration of App\Console\Commands\MyPages::crawled(App\Console\Commands\UriInterface $url, App\Console\Commands\ResponseInterface $response, ?App\Console\Commands\UriInterface $foundOnUrl = NULL) must be compatible with Spatie\Crawler\CrawlObserver::crawled(Psr\Http\Message\UriInterface $url, Psr\Http\Message\ResponseInterface $response, ?Psr\Http\Message\UriInterface $foundOnUrl = NULL)

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:9
     5| use Illuminate\Console\Command;
     6| 
     7| use \Spatie\Crawler\CrawlObserver;
     8| 
  >  9| class MyPages extends CrawlObserver{
    10| 
    11|     private $pages =[];
    12| 
20 Dec
1 month ago

ludo1960 left a reply on Instantiate Abstract Class

cool, thanks!

ludo1960 left a reply on Parent::child Pages

oh yes, apart from october.cms and a few others. i would just like to explore the possibilities within laravel, like how it manages parent:child pages i.e. one to many and many to many operations.

ludo1960 started a new conversation Parent::child Pages

Hi guys,

Coming from a Drupal background, getting to know Laravel. In Drupal they have Taxonomy system (ie the science of classification) it comes with a million and one add on modules. In Laravel I believe Taxonomies come as Categories. Can anybody point me in the direction of reading about how Laravel deals with Categories? Also is there a curated list of must have Category packages for the developer?

Thanks in advance

ludo1960 left a reply on Instantiate Abstract Class

Yes I do see what you mean, ultimately I would like to grab a title, the body and a category hierarchy, and save that in a database table, but at this stage I would be happy to get the ?£*^^++** thing working!

ludo1960 left a reply on Instantiate Abstract Class

If you look at https://github.com/spatie/crawler it says "spider_web Easily crawl the web using PHP spider Seems no one can tell me how to deal with abstract methods in the CrawlObserver class. And yes I would like to something useful with the crawler but that's for another day! For completeness here's the CrawlObserver class:

namespace Spatie\Crawler;

use Psr\Http\Message\UriInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;

abstract class CrawlObserver
{
    /**
     * Called when the crawler will crawl the url.
     *
     * @param \Psr\Http\Message\UriInterface $url
     */
    public function willCrawl(UriInterface $url)
    {
    }

    /**
     * Called when the crawler has crawled the given url successfully.
     *
     * @param \Psr\Http\Message\UriInterface $url
     * @param \Psr\Http\Message\ResponseInterface $response
     * @param \Psr\Http\Message\UriInterface|null $foundOnUrl
     */
    abstract public function crawled(
        UriInterface $url,
        ResponseInterface $response,
        ?UriInterface $foundOnUrl = null
    );

    /**
     * Called when the crawler had a problem crawling the given url.
     *
     * @param \Psr\Http\Message\UriInterface $url
     * @param \GuzzleHttp\Exception\RequestException $requestException
     * @param \Psr\Http\Message\UriInterface|null $foundOnUrl
     */
    abstract public function crawlFailed(
        UriInterface $url,
        RequestException $requestException,
        ?UriInterface $foundOnUrl = null
    );

    /**
     * Called when the crawl has ended.
     */
    public function finishedCrawling()
    {
    }
}

Again from https://github.com/spatie/crawler

The crawler can be instantiated like this

Crawler::create()
    ->setCrawlObserver(<class that extends \Spatie\Crawler\CrawlObserver>)
    ->startCrawling($url);

No mention of abstract methods that nobody can tell me how to use?????

ludo1960 left a reply on Instantiate Abstract Class

@ZION - the crawlobserver class?

19 Dec
1 month ago

ludo1960 left a reply on Instantiate Abstract Class

Ok Did that:

php artisan crawler:crawl
PHP Fatal error:  Class App\Console\Commands\myClass contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Spatie\Crawler\CrawlObserver::crawled, Spatie\Crawler\CrawlObserver::crawlFailed) in /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php on line 10

   Symfony\Component\Debug\Exception\FatalErrorException  : Class App\Console\Commands\myClass contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Spatie\Crawler\CrawlObserver::crawled, Spatie\Crawler\CrawlObserver::crawlFailed)

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:10
     6| 
     7| use \Spatie\Crawler\CrawlObserver;
     8| 
     9| 
  > 10| class myClass extends CrawlObserver {
    11| 
    12| }
    13| 
    14| 


   Whoops\Exception\ErrorException  : Class App\Console\Commands\myClass contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Spatie\Crawler\CrawlObserver::crawled, Spatie\Crawler\CrawlObserver::crawlFailed)

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:10
     6| 
     7| use \Spatie\Crawler\CrawlObserver;
     8| 
     9| 
  > 10| class myClass extends CrawlObserver {
    11| 
    12| }
    13| 
    14| 

How to find the 2 missing abstract methods?

ludo1960 started a new conversation Instantiate Abstract Class

Hi Guys,

After much reading and googling, hers's what's up: from https://github.com/spatie/crawler

Usage
The crawler can be instantiated like this

Crawler::create()
    ->setCrawlObserver(<class that extends \Spatie\Crawler\CrawlObserver>)
    ->startCrawling($url);
The argument passed to setCrawlObserver must be an object that extends the \Spatie\Crawler\CrawlObserver abstract class:

So in my CrawlerCommand.php I added:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use \Spatie\Crawler\CrawlObserver;


abstract class myClass extends CrawlObserver {

}

class CrawlerCommand extends Command
{

Then in my Handle Method I added:

    public function handle()
    {
        //code goes here
        $myObject = new myClass(); //Change myClass to Object
     
        $url = 'php.local.com/'; // Set to localhost site
        Crawler::create()
        ->setCrawlObserver($myObject)
        ->startCrawling($url);
    }

So when I run php artisan crawler:crawl I get the following error:

   Symfony\Component\Debug\Exception\FatalThrowableError  : Cannot instantiate abstract class App\Console\Commands\myClass

  at /var/www/test.local.com/app/Console/Commands/CrawlerCommand.php:56
    52|     public function handle()
    53|     {
    54| 
    55|         //code goes here
  > 56|         $myObject = new myClass(); //Change myClass to Object
    57|         //$myObject = new CrawlObserver(); //instantiate
    58|         $url = 'php.local.com/'; // Set to localhost site
    59|         Crawler::create()
    60|         ->setCrawlObserver($myObject)

  Exception trace:

  1   App\Console\Commands\CrawlerCommand::handle()
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

  2   call_user_func_array([])
      /var/www/test.local.com/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:29

Pretty sure i'm on the right track, but missing a fundamental step somewhere, any ideas guys?

18 Dec
1 month ago
17 Dec
1 month ago

ludo1960 started a new conversation Pass Argument As Object That Extends An Abstract Class

Hi guys,

If i have an abstract class 'myAbstractClass' how the heck do I pass an argument to a public function 'myPublicFunction' , and the argument needs to be an object that extends 'myAbstractClass' Hope that makes sense cos I am a bit lost!

16 Dec
1 month ago

ludo1960 left a reply on What's Supposed To Happen?

Ok, so the code in the handle method should be something along these lines:

class myClass extends CrawlObserver {
    public $url = 'http://somesite.com';
}

Crawler::create()
    ->setCrawlObserver(myClass)
    ->startCrawling($url);

Am I on the right track?

14 Dec
1 month ago

ludo1960 left a reply on Error In Shiow.blade

Well well well, thanks to you guys I've got a complete working App. A full roles and permissions system with Laravel GUI and MongoDB. If anyone wants a nice little playground using the aforementioned I'll stick it up on github, if you can show me how to do that, it will be another first.

Thanks guys?

ludo1960 left a reply on Error In Shiow.blade

And vajid wins the star prize.. A big THANK YOU for:

return redirect()->route('posts.show', $id);

Worked first time!

ludo1960 started a new conversation Error In Shiow.blade

Hi Folks, thanks to the guys here for all previous help. I'm trying to adapt a php script from a couple of years ago. Having solved most of the issues I've come across one that's got me stumped:

The error:

Illuminate \ Routing \ Exceptions \ UrlGenerationException
Missing required parameters for [Route: posts.show] [URI: posts/{post}].

In my PostController i have:

    public function show($id) {
        $post = Post::findOrFail($id); //Find post of id = $id
        return view ('posts.show', compact('post'));

    }

And in my show.blade I have:

<h1>{{ $post->title }}</h1>
<hr>
<p class="lead">{{ $post->body }} </p>
<hr>
{!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!}
<a href="{{ url()->previous() }}" class="btn btn-primary">Back</a>
@can('edit posts')
<a href="{{ route('posts.edit', $post->id) }}" class="btn btn-info" role="button">Edit</a>
@endcan
@can('delete posts')
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
@endcan
{!! Form::close() !!}
``` Finally in my update method:
   public function update(Request $request, $id) {
        $this->validate($request, [
            'title'=>'required|max:100',
            'body'=>'required',
        ]);

        $post = Post::findOrFail($id);
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->save();

        flash('Article, '. $post->title. ' updated')->success();
        return redirect()->route('posts.show');

    }

Any ideas guys?

13 Dec
1 month ago

ludo1960 left a reply on What's Supposed To Happen?

ok i'll give it a bash, thanks again for your heart!

12 Dec
1 month ago

ludo1960 left a reply on What's Supposed To Happen?

another excellent answer, only i can't find a tutorial that follows your recipe, ie adding command logic to the handle method

ludo1960 left a reply on What's Supposed To Happen?

@D9705996 - thanks for your considered answer, looks like i need to make a command, new territory for me, any pointers?

ludo1960 left a reply on What's Supposed To Happen?

@D9705996 - thanks for the link, it all makes sense apart from where to put the initial code, do i make a new test, a new model, a new controller? that's the bit i don't get? thanks

ludo1960 started a new conversation What's Supposed To Happen?

Hi Folks,

I installed https://github.com/spatie/crawler and found this This test here https://github.com/spatie/crawler/blob/master/tests/CrawlerTest.php So I save this file as tests/CrawlerTest.php and run vendor/bin/phpunit from a terminal and I get "2 tests 2 assertions" I thought I would get a report on the links in my test site? Am I doing this right?

06 Dec
1 month ago

ludo1960 left a reply on Get Id Of Newly Created Record

Doing it the easy way, following https://github.com/mostafamaklad/laravel-permission-mongodb :

        $user->roles()->syncRoles($roles);

results in :

BadMethodCallException
Call to undefined method Jenssegers\Mongodb\Relations\BelongsToMany::syncRoles()

So I guess the only solution is to loop through the array:

         if (isset($roles)) {
            foreach ($roles as $role) {
                $role_r = Role::where('id', '=', $roles)->get()->pluck('name');
                $user->assignRole($role_r);
                flash('I am in the loop,'. $role_r)->success();
            }
         }

The flash line prints out "I am in the loop,[]" so it looks like the Role & Permissions package has blocked the query, dunno what to try next!

05 Dec
1 month ago

ludo1960 left a reply on Get Id Of Newly Created Record

The reason I'm befuddled is I have an update method that successfully assigns role to the user so:

        if (isset($roles)) {
  
            foreach ($roles as $role) {
            $role_r = Role::where('_id', '=', $role)->firstOrFail();
            $user->assignRole($role_r); //Assigning role to user
            }
          }

Using the same code in the store method just does not work, I even added a flash message to print out $role_r:

 flash($role~_r)->success();

and it prints out the correct value,

ludo1960 left a reply on Get Id Of Newly Created Record

Hmm, I'm missing something:

        $id = $user->id;

    //Checking if a role was selected
        if (isset($roles)) {
            foreach ($roles as $role) {
                $role_r = Role::where('_id', '=', $role)->get()->pluck('name');
                $user->assignRole($role_r); //Assigning role to user
            }
        }

Role is not updated for user

ludo1960 started a new conversation Get Id Of Newly Created Record

Hi folks,

If you create a new record so:

        $user = User::create($request->only('email', 'name', 'password')); //Retrieving only the email and password data

How to then grab hold of that record to add something to it?

02 Dec
1 month ago

ludo1960 left a reply on Return Values For An Array Of Ids

Nope,

$myarray = array(1001, 1004);

        Table::whereIn('name', $myarray)->get();

 print_r($myarray);

Still got (1001, 1004) in $myarray, I'm using MongoDB if that makes a difference?

ludo1960 started a new conversation Return Values For An Array Of Ids

Hi guys, If I have an array of ids array(1001 1004) and want to transform that array to matched values in a table:

ID      ColA            
1001    apple       
1002    pear        
1003    orange
1004    banana

So the array becomes array(apple, banana)

foreach ( $id as $ids) {

  // Code goes here
}

ludo1960 left a reply on Pass Hidden Value In Blade Template

I tried you suggestion:

{{ Form::checkbox('checked_permissions[]', $permission->id, $role->permissions) }}
{{ Form::hidden('permissions[]', $permission->name) }}

and when I visit the form all check boxes are ticked, not the permission allocated to that role. Then I tried:

        {{ Form::checkbox('permissions[]', $permission->id, $role->permissions) }}
        {{ Form::hidden('mypermissions[]', $permission->name) }}
        {{ Form::label($permission->name, ucfirst($permission->name)) }}<br>

in the form blade, and in the update method i put:

        $name = $request['name'];
        $role = Role::findByName($name);

        $permissions = $request['mypermissions'];

        $role->syncPermissions($permissions);

        flash( 'Role'. $role->name.' updated!')->success();
        return redirect()->route('roles.index');

now irrespective of what permission I tick, all permission are granted to the role, eek!

ludo1960 started a new conversation Pass Hidden Value In Blade Template

Thanks to the good folk here I am starting to make progress on my pet project, here's my latest little problem. In my roleController UPDATE method I have:

        $role = Role::findOrFail($id);
        $permissions = Permission::all();
        return view('roles.edit', compact('role', 'permissions'));
    }

    public function update(Request $request, $id) {

        //dd($id);

        $role = Role::findOrFail($id);//Get role with the given id

        $this->validate($request, [
            //'name'=>'required|max:10|unique:roles,name,'.$id,
            'permissions' =>'required'
        ]);

        $name = $request['name'];
        $role = Role::findByName($name);

        $permissions = $request['permissions'];

        $role->syncPermissions($permissions);

        flash( 'Role'. $role->name.' updated!')->success();
        return redirect()->route('roles.index');
    }```

and in my edit blade I have:

```    {{ Form::model($role, array('route' => array('roles.update', $role->id), 'method' => 'PUT')) }}

    <div class="form-group">
        {{ Form::label('name', 'Role Name') }}
        {{ Form::text('name', null, array('class' => 'form-control')) }}
    </div>

    <h5><b>Assign Permissions</b></h5>
    @foreach ($permissions as $permission)

        {{ Form::checkbox('permissions[]', $permission->id, $role->permissions) }}
        {{ Form::hidden('permissions[]', $permission->name) }}
        {{ Form::label($permission->name, ucfirst($permission->name)) }}<br>

    @endforeach
    <br>
    {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }}

    {{ Form::close() }}```

The blade file is passing back the permission->id as you would expect. I need the id to associate the permissions to the role. However I would like to pass back the permission->name to the roleController permissions array. I've made lots of wrong guesses so time to call in the pros. When you are trying to learn a new php framework wrong guesses are a must cos sometimes you get it right, but not this time :)
30 Nov
1 month ago

ludo1960 left a reply on Validation In Controller

Thanks again guys, I think @munazzil is on the right track with the two tables so here is the details of the tables form the migration files:

    {
        $collectionNames = config('permission.collection_names');

        Schema::table($collectionNames['roles'], function (Blueprint $collection) {
            $collection->unique(['name', 'guard_name']);
        });

        Schema::table($collectionNames['permissions'], function (Blueprint $collection) {
            $collection->unique(['name', 'guard_name']);
        });
    }

the rout is a simple:

```finally the form:
```@extends('adminlte::page')

@include('flash::message')

@section('title', '| Edit Role')

@section('content')

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif


<div class='col-lg-4 col-lg-offset-4'>
    <h1><i class='fa fa-key'></i> Edit Role: {{$role->name}}</h1>
    <hr>

    {{ Form::model($role, array('route' => array('roles.update', $role->id), 'method' => 'PUT')) }}

    <div class="form-group">
        {{ Form::label('name', 'Role Name') }}
        {{ Form::text('name', null, array('class' => 'form-control')) }}
    </div>

    <h5><b>Assign Permissions</b></h5>
    @foreach ($permissions as $permission)

        {{Form::checkbox('permissions[]',  $permission->id, $role->permissions ) }}
        {{Form::label($permission->name, ucfirst($permission->name)) }}<br>

    @endforeach
    <br>
    {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }}

    {{ Form::close() }}
</div>

@endsection

Adding dd($id) to the form results in "5bffb06973d4f931fa1f9428" which matches the corresponding role in the role table