Trying to get property 'access_token' of non-object laravel-google-sheets - laravel

Good Night,I'm using google api sheets with laravel following this tutorial
https://github.com/kawax/laravel-google-sheets
when I try to do the first example
use Sheets;
$user = $request->user();
$token = [
'access_token' => $user->access_token,
'refresh_token' => $user->refresh_token,
'expires_in' => $user->expires_in,
'created' => $user->updated_at->getTimestamp(),
];
// all() returns array
$values = Sheets::setAccessToken($token)->spreadsheet('spreadsheetId')->sheet('Sheet 1')->all();
my code:
namespace App\Http\Controllers;
use Sheets;
use Google;
class PlanilhaController extends Controller
{
public function index(Request $request)
{
$user = $request->user();
$token = [
'access_token' => $user->access_token,
'refresh_token'=> $user->refresh_token,
'expires_in'=> $user->expires_in,
'created' => $user->updated_at->getTimestamp(),
];
$values = Sheets::setAccessToken($token)
>spreadsheet('spreadsheetId')->sheet('Sheet 1')->all();
// all() returns array
return view('planilha', compact('values'));
}
error: Trying to get property 'access_token' of non-object
which is not requested, but I do not know how to solve it

Actually you do not need that token, what you need is to set up your .env so it has following key
GOOGLE_APPLICATION_NAME=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT=
GOOGLE_DEVELOPER_KEY=
GOOGLE_SERVICE_ENABLED=
GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION=
POST_SPREADSHEET_ID=
POST_SHEET_ID=
then in your controller
$sheets = Sheets::spreadsheet(config('sheets.post_spreadsheet_id'))
->sheet(config('sheets.post_sheet_id'))
->get();
$header = $sheets->pull(0);
$posts = Sheets::collection($header, $sheets);
$posts = $posts->reverse()->take(10);
then in your config file write this
'post_spreadsheet_id' => env('POST_SPREADSHEET_ID'),
'post_sheet_id' => env('POST_SHEET_ID'),

Related

Laravel 8 multiple models to single view Error $address Not defined

I'm trying to create 2 rows in the DB using findOrNew() but when I use the ID from the Users model to create another model(Address) the programs returns undefined variable $address. I don't know if I'm using the correct approach or not. Bellow you can view my approach. Can you lead me to the right approach or where to find it?
2 models one view:
seeing what you have in your method is returning an undefined because it is not executing the findOrNew method correctly, check this link, maybe it will help you and this same
the second is that if you are passing the values by post everything will come to you in the $req parameter and only there then if you want to use the id you would have to access through $req->id if you send the data correctly
the third I see that in the view method you are passing 3 parameters when you should only pass two the first the name of the view the second the arrangement with the data that you will pass to the view
public function detail(Request $req)
{
$user = User::firstOrNew($req->id);
$user->user_type_id = 1;
$user->name = $req->name;
$user->last_name = $req->last_name;
$user->email = $req->email;
$user->password = Hash::make(Str::random(8));
$user->save();
$address = UserAddress::firstOrCreate(['user_id' => $req->id]); //or maybe $user->id
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}
finally you may prefer to use the updateOrCreate method
public function detailV2(Request $req)
{
$user = User::updateOrCreate(
['id' => $req->id],
[
'user_type_id' => 1,
'name' => $req->name,
'last_name' => $req->last_name,
'email' => $req->email,
'password' => Hash::make(Str::random(8)),
]
);
$address = UserAddress::firstOrCreate(['user_id' => $user->id]);
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}

Convert API resource to array

I want to store data on Firestore. I need to send an array to Firestore. I have API resources and I wanted to use it.
My ApiResource:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'phone' => $this->phone,
'addresses' => AddressResource::collection($this->addresses),
];
}
Firestore store data:
public function set(User $user){
$this->firestore->document($user->id)->set((new UserResource($user)));
}
It is an error:
Argument 1 passed to
Google\Cloud\Firestore\DocumentReference::set() must be of the type
array, object given,...
You can call the toJson() on your Api Resource object:
$data = MyModel::with('addresses')->find(1);
$myArray = json_decode((new MyModelResource($data))->toJson(), true);
So you could just:
$this->firestore->document($user->id)->set($myArray);
Do it:
public function set(User $user){
$this->firestore->document($user->id)->set(toArray($user));
}

How to access this value?

I am stuck with this task. While logging out, I have to access this $time value which I define in other file when user logged in. I need to use its value in logout function.
How can I do this? I've read about accessors but my attempts to use it weren't successful.
BroadcastServiceProvider
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
return [
'user_id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
In LoginController
public function logout() {
$id = auth()->id();
$user_info = \App\UserInfo::where('user_id', $id)->first();
$user_info->save();
auth()->logout();
session()->put('left',now());
return redirect('/');
}
The best way is that store it on your database but you can store it in session like this:
// Retrieve a piece of data from the session...
$value = session('time-'.$user->id);
// Store a piece of data in the session...
session(['time-'.$user->id => now()]);
I figured it out. There is an easy way to do this without accessors.
$user_info = \App\UserInfo::where('user_id', $id)->latest()->first();

Passing return data to another function in same controller laravel

Try to connect to external API.
In first function, I already received token with authentication.
To send POST request, I need to put xtoken that I received from first function as second function.
I don't know how to send value to second function (registerUser)
Route::get('/connect', 'Guzzlecontroller#registerUser')->name('registeruser');
this is my route file
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use App\Http\Controllers\Auth\RegisterController;
class GuzzleController extends Controller
{
public function Gettoken()
{
$client = new \GuzzleHttp\Client();
$request = $client->get(
'http://api01.oriental-game.com:8085/token',
[
'headers' => [
'X-Operator' => 'mog189b',
'X-key' => 'sQxAVNaEMe0TCHhU',
]
]
);
$response = $request->getBody();
$tokenReturn = json_decode($response, true);
$xtoken = array("x-token:" . $tokenReturn['data']['token'],);
$this->registerUser($xtoken);
}
public function registerUser($xtoken)
{
$client = new \GuzzleHttp\Client();
$url = "http://api01.oriental-game.com:8085/register";
$request = $client->post($url, [
'headers' => $xtoken,
'body' => [
'username' => 'test1',
'country' => 'Korea',
'fullname' => 'test user1',
'language' => 'kr',
'email' => 'testuser1#test.com',
]
]);
$response = $request->send();
dd($response);
}
}
Too few arguments to function App\Http\Controllers\GuzzleController::registerUser(), 0 passed and exactly 1 expected
this is error I am getting.
please help me to how to send $xtoken value to registerUser function
The problem is Laravel is calling registerUser directly instead of going through getToken. So the token is never retrieved and passed to the register action.
Instead of calling registerUser() from Gettoken(). Have Gettoken() return the token and call it from registerUser()
public function Gettoken()
{
...
return $xtoken;
}
public function registerUser()
{
$xtoken = $this->Gettoken();
...
}

Laravel Dingo API is not returing UTF8 encoded characters

I've just inherited a project in Laravel and it's using Dingo API.
The API is returning strings like Federaci\u00f3ninstead of FederaciĆ³n.
All strings are correctly UTF-8 encoded in the database, so the problem is in the server.
The controller is returning $this->response->paginator($articles, new ArticlesCollectionTransformer); and inside ArticlesCollectionTransformer I placed a var_dump for the strings I have issues with and they are correctly encoded there.
Where else should I look? What am I missing?
Controller:
public function index(Request $request)
{
$limit = (0 === (int)$request->limit || $request->limit > self::PER_PAGE) ? self::PER_PAGE : $request->limit;
$articles = Article::with('author', 'category')
->approved()
->orderBy('published_at', 'desc')
->orderBy('featured', 'desc')
->paginate($limit);
return $this->
response->
paginator($articles, new ArticlesCollectionTransformer)->
// also tried:
// withHeader('Content-type', 'application/json; charset=utf-8');
}
Transformer
class ArticlesCollectionTransformer extends TransformerAbstract
{
public function transform (Article $article)
{
// var_dump($article->title) ==> is correctly encoded
return [
'id' => (int) $article->id,
'category' => $article->category->name,
'author' => $article->author->name ?? ArticleAuthor::DEFAULT_AUTHOR_FOR_NEW_ARTICLES,
'display_order' => (int) $article->display_order,
'title' => $article->title,
'featured' => (bool) $article->featured,
'viewed_times' => (int) $article->viewed_times,
'last_update' => $article->updated_at->timestamp,
];
}
}
More info:
Laravel: 5.2.*
dingo/api: 1.0.x#dev

Resources