shweshi / OpenGraph

A Laravel package to fetch Open Graph data of a website.
https://opengraph.shashi.dev
MIT License
154 stars 29 forks source link

Error when using #82

Closed LeonardoSartor closed 2 years ago

LeonardoSartor commented 2 years ago

Hello how are you? I started getting this error when using...

[2022-03-18 21:45:05] local.ERROR: Using $this when not in object context {"exception":"[object] (Error(code: 0): Using $this when not in object context at [...]back-end\vendor\shweshi\opengraph\src\OpenGraph.php:12)

Laravel 8.x My code: if (!$validator->fails()) { $data_group = OpenGraph::fetch($request->link); $validator->after(function ($validator) use ($data_group) { if(empty($data_group['title'])) { $validator->errors()->add('link', 'Error'); } }); } I don't understand its origin or how to solve it...

shweshi commented 2 years ago

Hi @LeonardoSartor Thanks for using OpenGraph. I checked the library its working fine with Laravel 8.x also tried with validation logic. Seems to be working fine. Do you mind sharing some more code snippet how you are trying to use the library, or share a sandbox code to debug it.

Here is the snippet I have tried with:

Route::get('/fetch', function (Request $request) {

    $validator = Validator::make($request->all(), [
        'link' => 'required',
    ]);

    if (!$validator->fails()) { 
        $data_group = OpenGraph::fetch($request->link);
        $validator->after(function ($validator) use ($data_group) { 
            if(empty($data_group['title'])) { 
                $validator->errors()->add('link', 'Error');
            }
            return response()->json($data_group);
        });
    }
});

Few things you can check:

  1. You are not calling it inside a static function
  2. Check if you are using it inside a Closure I guess PHP 7 should support it but have a check.
  3. Try importing use OpenGraph;
LeonardoSartor commented 2 years ago

Thank you very much @shweshi! My mistake was calling it inside a static function... What a silly mistake... but for a beginner, I think it's okay!

I solved it by changing the code to:

if (!$validator->fails()) {
  $data_group = new OpenGraph();
  $data_group = $data_group->fetch($request->link);
    $validator->after(function ($validator) use ($data_group) {
      if(empty($data_group['title']))   {
      $validator->errors()->add('link', 'Error.');
    }
  });
}

From my heart, thank you very much for your help, it will be of great help for a personal project, it made me see the error and fix it!

shweshi commented 2 years ago

@LeonardoSartor Glad it helped.

Happy Coding