My relationship is not working? - laravel

When i write this code my relationship is not working. How can i write this part of code so that i can access to $article->translations(). Any suggestion?
$date_number = strval(date('m', strtotime($month)));
$articles = DB::table('articles')->whereRaw('MONTH(created_at) ='.$date_number)->where('approved',1)->get();
foreach($articles as $article){
$article->trans = $article->translations()->whereHas('language',function($query) use($current_language_id){
$query->where('id','=',$current_language_id);
})->first();
}
I got it. When i use $articles = Articles::whereRaw('MONTH(created_at) ='.$date_number)->where('approved',1)->get();

When you use query builder's get method it returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object not an Eloquent Model object.
So you can't use the relations on StdClass object, you need an Eloquent object. And for that you should use Eloquent query builder as:
$articles = Article::whereRaw('MONTH(created_at) ='.$date_number)
->where('approved',1)
->get();

Related

Object of class stdClass could not be converted to string ERROR when running laravel query

I am using a query in Laravel, but when I try to dump it shows this error
'Object of class stdClass could not be converted to string'
This is the query ->
$staff = User::find($id);
$departments = Department::all();
$managers = DB::table('users')
->where('role', 'manager')
->get();
$staffId = DB:: table('users')
->where('id', $id)
->select('deptId')
->get();
$empDept = DB::table('departments')
->join('users','users.deptId','=','departments.id')
->select('department_name')
->where('departments.id', $staffId)
->orWhere('users.deptId', '=', 'departments.id')
->pluck('departments.department_name')
->first();
dd($empDept);
What could the problem be?
You are passing a Collection of stdClass objects to the where method on the query you are building. It is iterating that Collection and trying to use the values as strings but they are stdClass objects which can not be converted to strings. You should be passing a single value to the where condition:
$staffId = $staff->deptId;
Now you are getting the deptId value from the User object you already have instead of querying the table again.
If you really wanted to query the table again you could just ask for the single value instead of the entire record using the value method:
$staffId = DB:: table('users')
->where('id', $id)
->value('deptId');
I think you need to decode your data first
$code = json_decode($query, true);

Eloquent accessing array inside object

I have a get formule that returns some nested relationships in an array. I was wondering how to access them in a where statement.
The initial get
$taken = UserWork::with('work.place')
->with('user')
->with('work.timeslot')
->get();
I tried something like this
$taak = $taken->where('work.timeslot[0].start_hour',"17:00:00")->first();
json result from $taken
Using with will endup with two queries. if you want to bring the user with timeslot null then there no need to add whereHas
$callback = function($query) {
$query->where('start_hour',"17:00:00");
};
$taken = UserWork::whereHas('work.timeslot', $callback)
->with(
['work.place', 'user', 'work.timeslot' => $callback]
)->get();

How can I use laravel db query ->update() method in if statement

I want to check something in if, and if that condition is true I want to update the record that was fetched before.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (this condition will pass I want to update this record) {
$resultQuery->update(array('price_usd' => $card->prices->usd));
}
When I use the ->update() like this, I get an error:
Call to undefined method stdClass::update();
How can I do this ?
The first() function on laravel query builder returns a stdClass meaning Standard Class.
There is no function called update() in stdClass in php. You have called update() on stdClass, and that causes the error.
There are several ways to achieve your goal.
Use Laravel query builder update() function.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (your_condition) {
Db::table('cards')
->where('api_id', $card->id)
->update([
'price_usd' => $card->prices->usd
]);
}
If you don't want to fetch the card data, don't call first()
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if (your_condition) {
$resultQuery
->update([
'price_usd' => $card->prices->usd
]);
}
Use Eloquent models (Laravel's preferred way)
Create an Eloquent model for Cards (if you have not done already).
public class Card extends Model
{
}
Use eloquent query builder to fetch data. And use model update() function to update data.
$resultingCard = Card::where('api_id', $card->id)->first();
if (your_condition) {
$resultingCard->update([
'price_usd' => $card->prices->usd,
]);
}
If you're using model
You can add in card controller
$card = Card::where('api_id', $card->id)->first();
if (someConditional)
{
// Use card properties, number is a example.
$card->number = 10
// This line update this card.
$card->save();
}
You can learn more about eloquent here.
Something like this:
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if ($resultQuery->count()) {
$object = $resultQuery->first();
$object->price_usd = $card->prices->usd;
$object->save();
}
Or look for an alternative solutions here: Eloquent ->first() if ->exists()

Laravel isNotEmpty() not working on Eloquent model

I'm probably confused by Eloquent (again...) but I thought that this should work:
$test_row = Test::
where('status', 'active')
->where('condition2', 'value')
->orderBy('order', 'asc')
->first();
if($test_row->isNotEmpty())
return $test_row;
But is it throwing the following error: Call to undefined method App\Test::isNotEmpty().
By using first() it will return an Eloquent model right? And isNotEmpty(), as well as isEmpty(), should be able to be used on the returned model?
You are trying to call isNotEmpty() on a model object and not a collection, when you use first() it returns an object not a collection.
Use
if($test_row)
{
return $test_row
}
The method isNotEmpty() is actually returned by Laravels Collection class and not by an Eloquent model. Since you're not asking for multiple results, only the model is returned instead of a collection.
Simply use
if ($test_row) {
return $test_row;
}
to check if the query had any results and the model exists.

How to return collection instead array from DB Laravel?

If to use basic queries using use Illuminate\Support\Facades\DB; we get result as array instead collection. How to return collection?
$users = DB::select('select * from users where active = ?', [1]);
It returns array of $users (rows).
Wrapping your array of results using collect() should do it
collect($users);

Resources