Below is my function in my controller.
public function getUserTimesheet($userId)
{
$user = User::find($userId);
if($user) {
$userTimesheets = $user->userTimesheets->where('created_at', '>=', Carbon::now()->month());
return response()->json([
"status" => true,
"data" => [
"user-timesheets" => $userTimesheets
]
], 200);
}
return response()->json([
"status" => false,
"message" => "User not found"
], 401);
}
I did create model for the same function.
Multiple timesheets will be uploaded for the same user but I want to return the data of latest upload. I have crated_at column in my respective database and want to compare it to get latest timesheet information by comparing months.
I am getting an error of call to a member function where() on null.
Am new to laravel and creating APIs. Thank you.
The error suggests that the userTimesheets relationship on the particular user is null. Check whether the user has any timesheets, if they have any check how the userTimesheets relationship is defined.
Related
I select an array with categories via json_decode and attach them to the article.
public static function setArticleCategory(Request $request) {
$article = Article::where('id', $request->article_id)->first();
if(!$article){
return response()->json([
'message' => 'Article not found'
], 404);
}
$categories_ids = json_decode($request->categories_ids);
$article->categories()->attach($categories_ids);
return response()->json([
'message' => $categories_ids
], 200);
}
The question is, how can I check in categories_ids, for example, if one of the selected categories does not exist in the array?
The fastest way would be to use count()
$categories_ids = json_decode($request->categories_ids);
if (count($categories_ids) != Category::whereKey($categories_ids)->count()) {
//return error.
}
It would not tell you wich one is the non existing category, but it will trigger an error if at least one of them doesnt exist.
Edit (comment)*
if you want to ignore the non existing IDs, use this
$categories_ids = json_decode($request->categories_ids);
$categoryPK = (new Category())->getKeyName();
$categories_ids = Category::whereKey($categories_ids)->pluck($categoryPK)->toArray();
It will return an array of ids that exists in the database based on the input (you need to check for empty array after that).
Im facing a weird maybe a bugs or my mistake where Eloquent create return wrong ID. It's happen when I put DB::listen in service provider class and store in database any queries detected in DB::listen.
BUT the weird is When i trying to insert like this User::create($input), it's return the ID of QueryActivity not the ID of User. For example the ID should be 20 but its return 100 from table QueryActivity
logs from User::create($input)
[2020-02-23 12:42:46] staging.INFO: {"first_name":"Testing","last_name":"Tesgin","username":"Testing","staff_id":"12313123","mobile_phone":"01231232323","active":true,"email":"testing#gmail.com","created_by":1,"updated_at":"2020-02-23 12:42:46","created_at":"2020-02-23 12:42:46","id":123,"fake_password":"5ebe2294ecd0e0f08eab7690d2a6ee69"}
Above Logs, the highlighted only the ID is wrong. Other detail is correct.
Eloquent
$user = User::create($input);
And in my ObserverServiceProvider.class
DB::listen(function ($query) {
try {
if (preg_match('(query_activities)', $query->sql) == 0) {
QueryActivity::createUsingQueryBuilder([
'connection_name' => $query->connectionName,
'time_taken' => $query->time,
'query' => $query->sql,
'bindings' => Utils::aesEncrypt(json_encode($query->bindings)),
'created_at' => now(),
'updated_at' => now(),
]);
}
} catch (\Exception $exception) {
LogCentre::channel('query')->info($exception->getMessage());
}
});
in QueryActivity class
class QueryActivity extends Model
{
protected $fillable = [
'connection_name',
'time_taken',
'query',
'bindings'
];
public static function createUsingQueryBuilder(array $activity)
{
DB::connection((new self)->getConnectionName())->table((new self)->getTable())->insert($activity);
}
}
Is there anyone facing this issues?
SOLUTION:
Based on issues in https://github.com/laravel/framework/issues/25768#issuecomment-424179984
Change connection name then its working..
I am having a very weird experience with my code today. I could swear all worked well until today.
Here's the thing, I have a one to one relationship between User and BankAccount model like this
public function bankAccount()
{
return $this->hasOne(BankAccount::class, 'user_id');
}
When a user account is created initially, there is no record in the bank_accounts table for the user. A user can then create the bank account record with this method
public function update(Request $request, User $user)
{
// create record if user does not have a bankAccount
if (!$user->bankAccount) {
$user->bankAccount()->create($request->all());
} else {
$user->bankAccount()->update($request->all());
}
return new BankAccountResource($user->bankAccount);
}
And the BankAccountResource
public function toArray($request)
{
return [
'user_id' => $this->user_id,
'bank_name' => $this->bank_name,
'bvn' => $this->bvn,
'account_no' => $this->account_no
];
}
The problem I am experiencing is that when the user creates the bank account record the first time with $user->bankAccount()->create($request->all()); I get the following error exception
"message": "Trying to get property 'user_id' of non-object"
But in the db, the record is actually created so I wonder why the error is thrown.
For update $user->bankAccount()->update($request->all());, I get the proper response returned which looks like this
{
"user_id": 13,
"bank_name": "bank name",
"account": 1324354611
}
How can I fix this behavior?
I think that the correc is create $user, after created you can us your user and your relationship to create bankAccount:
$user = User::create($request->all());
$userBank = $user->bankAccount()->create($request->all());
You need to have the $user before, to use it.
I am using laravel apiResources for an api call, the problem is that i created a custom method named closePeriod, that when i try to fetch a period it return always
No query results for model [App\Entities\Accounting\Period]
this is the method, i try to get the Period with Period::findOrFail($id), i have checked and $id has a value, and it exists in the database
Route::get('periods/close/{id}', 'PeriodController#closePeriod');
public function closePeriod($id) {
if($period = Period::findOrFail($id)) {
//do something
return response()->json([
'error' => false,
'data' => $period
]);
}
return response()->json([
'error' => true,
'message' => 'The period was not found, please reaload and try again'
]);
}
I have noticed that the api methods does work fine, i get the periods in index, show and can create and edit a period so i think the problem is in the custom method? why?
I have InitResource that return basic data like some app data like app name etc..
Now if user is logged in, I return resource with user data or without user data, but when the user is null or auth()->user() is null, I get some error:
Cant return id of null
public function __get($key)
{
return $this->resource->{$key};
}
And when user is logged it works like it should.
Logically I am trying to return resource without data, but can I use it with some "default values" ?
In resource I am checking:
$data = [
'appName' => config('app.name'),
'locale' => app()->getLocale(),
];
if($this->hasRole('basic')) {
$data['user'] = $this->only(['username', 'fullname', 'avatar']);
}
return $data;
Can this be done in resource? With passed null? Thanks