0

I'm sure I'm missing something really simple here:

Shouldn't Auth::user() be available in the constructor below?

When I dd(Auth::user()) I get null. Why is that, and how can I setup my $dataService variable like I've shown in the constructor below?

Really new to PHP and Laravel

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\DataService\DataService;

class QuickBooksAPIController extends Controller
{
    public $dataService;

    public function __construct()
    {
        $this->dataService = DataService::Configure(array(
            'auth_mode'       => 'oauth2',
            'ClientID'        => env('QUICKBOOKS_CLIENT_ID'),
            'ClientSecret'    => env('QUICKBOOKS_CLIENT_SECRET'),
            'accessTokenKey'  => Auth::user()->access_token_key,
            'refreshTokenKey' => Auth::user()->access_token_secret,
            'QBORealmID'      => Auth::user()->target_realm,
            'baseUrl'         => "Development"
        ));
    }

    public function getInfo()
    {
        $this->dataService->setLogLocation("../../../storage/logs/quickbooks.log");
        $this->dataService->throwExceptionOnError(true);

        $companyData = $this->dataService->getCompanyInfo();

        return response([
            'company'  => $companyData,
        ], 200);
    }

EDIT:

Per @Medhi's response this is the way to get the values you need. Basically, you can't get Auth values in the constructor and you'll need to build a function for it.


<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\DataService\DataService;

class QuickBooksAPIController extends Controller
{
    public function dataService()
    {
        return DataService::Configure(array(
            'auth_mode'       => 'oauth2',
            'ClientID'        => env('QUICKBOOKS_CLIENT_ID'),
            'ClientSecret'    => env('QUICKBOOKS_CLIENT_SECRET'),
            'accessTokenKey'  => Auth::user()->access_token_key,
            'refreshTokenKey' => Auth::user()->access_token_secret,
            'QBORealmID'      => Auth::user()->target_realm,
            'baseUrl'         => "Development"
        ));
    }

    public function getInfo()
    {
        $this->dataService()->setLogLocation("../../../storage/logs/quickbooks.log");
        $this->dataService()->throwExceptionOnError(true);

        $companyData = $this->dataService()->getCompanyInfo();

        return response([
            'company'  => $companyData,
        ], 200);
    }

    public function batchInvoices()
    {
        $batch = $this->CreateNewBatch();

        $invoices = \App\Models\Invoice::all()->take(30);

        foreach ($invoices as $invoice) {
            $newInvoice = Invoice::create([
                "Line" => [
                    [
                        "Amount" => $invoice->amount,
                        "DetailType" => "SalesItemLineDetail",
                        "SalesItemLineDetail" => [
                            "ItemRef" => [
                                "value" => 1,
                                "name" => "Services"
                            ]
                        ]
                    ]
                ],
                "CustomerRef" => [
                    "value" => 1
                ]
            ]);
            $batch->AddEntity($newInvoice, $invoice->invoice_number, "Create");
        }

        // Run a batch
        $batch->Execute();
        $error = $batch->getLastError();
        if ($error) {
            return response(['error' => $error], 500);
        }
    }

    public function getAllByCategory(Request $request, $category)
    {
        $this->dataService()->setLogLocation("../../../storage/logs/quickbooks.log");
        $this->dataService()->throwExceptionOnError(true);
        $allOfCategory = $this->dataService()->Query("SELECT * FROM " . $category, $request->currentPage, $request->perPage);
        $countOfCategory = $this->dataService()->Query("SELECT COUNT(*) FROM " . $category);

        return response([
            $category  => $allOfCategory,
            "count" => $countOfCategory,
        ], 200);
    }

    public function batchDelete(Request $request)
    {
        logs($request);
    }
}
Riza Khan
  • 2,712
  • 4
  • 18
  • 42
  • 1
    if it returns null, then no use is authentified. i dont see the issue here. maybe you need to set the right guard (if you have multiple) – N69S Sep 04 '21 at 14:10
  • 1
    The auth-user is generated when the authenticate middleware runs. Controller constructor ran before middlewares. https://stackoverflow.com/a/51496305/3231397 https://laravel.com/docs/master/controllers#controller-middleware – Mehdi Daalvand Sep 04 '21 at 14:53
  • 1
    never use env values directly. try to access them via config – Nipun Tharuksha Sep 04 '21 at 14:57
  • @Medhi Thank you, that solved my problem! If you want to type it out below, I'll be happy to mark you response as the answer – Riza Khan Sep 04 '21 at 15:03
  • 1
    @RizaKhan super personal recommendation, move your `__constructor` stuff to a `Service` class (a normal class). You would use this class just for getting this stuff, so you instantiate the class inside your specific controller's method (not `__constructor`) and then you use it normally. That would be a called Service Layer. – matiaslauriti Sep 05 '21 at 07:09
  • @matiaslauriti Would using a service provider be similar to your suggestion? – Riza Khan Sep 06 '21 at 03:00
  • @matiaslauriti Actually, I tried creating a service provider, but it looks like its not the way to go. However, I ended up putting that logic in the base Controller and that seems to help me use that config in any other controller. – Riza Khan Sep 06 '21 at 03:51
  • 1
    @RizaKhan no, a service provider is other stuff, that is why I said a Service class (normal class), read my previous comment again. – matiaslauriti Sep 06 '21 at 04:21

0 Answers0