Retrieving rows from DB which contains same value in Laravel - php

Trying to retrieve rows which has same value(関西).
First I created a blade for this (kansai.blade)
And then I set the route:
Route::get('/kansai', 'PagesController#kansai');
I set the controller:
public function kansai()
{
$estates = allestates::where('region', '=', '関西')->get();
return view('pages.kansai', compact('estates'));
}
After that gave the link in main.blade:
<li>関西</li>
But it returns with an error:
Trying to get property of non-object (View:
/var/www/html/laravel/resources/views/welcome.blade.php)
Do I missing something here? The problem is my controller I guess?
Any idea? Thank you.

estates is an array not an object in this context. either loop trough it or specify an index.

I solved the problem, it's likely my mistake actually.
I already retrieved the data in kansai.blade.
So I just the pass the link in main.blade
which is like below.
<li>関西</li>
and with this problem solved.

Related

Is it possible to do pagination in laravel with groupBy in blade view?

I'm fetching record for multiple section in a view. To show complete data I am simply doing
$data = Data::all();
Then simply getting counts for each section as required.
For example:
{{count($data->where('status', 'HOLD'))}}
For another section on the same view I want to show result with Groupy
For Example:
#foreach($data->paginate()->groupBy('user_id') as $byUser)
#endforeach
Then show the pagination
{{$data->links()}}
I have already tried by separating the result in the controller and Calling the data using different methods.
$data = Data::all();
$userData = Data:paginate(5)->groupBy('user_id');
return view('data.all', compact('data', 'userData'));
This is working well without pagination. After adding pagination I am getting below error.
Method Illuminate\Database\Eloquent\Collection::paginate does not exist. (View: C:\xampp\htdocs\project\resources\views\data\all.blade.php)
Is there any way to work it out? Thanks.
Check this line:
$data = Data::all();
Here you are already executing the query, this means, a Collection instance is returned. That's why you can't use the paginate() method, because that is a QueryBuilder method.
Try this:
$userData = Data::groupBy('user_id')->paginate(5);
return view('data.all', compact('data', 'userData'));

Codeigniter: Call to a member function result_array() on boolean in

I'm developing a website using Codeigniter framework. I wanna ask, I just got this message suddenly when I reload the page:
Call to a member function result_array() on boolean in
And even if I change into $this->db->result(), I still got the message:
Call to a member function result() on boolean in
and so when I call other sql query result function. Please help me, if anyone know the tricks and hints to solve this. Thanks.
It is really hard to answer without seeing the code. But hope this helps.
Try like this.
$query = $this->db->get('tablename');
$query->result();
or
$this->db->get('tablename')->result();
I php codeIgniter:-
result_array:-
This function returns the query result as a pure array, or an empty array when no result is produced. Typically you'll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
Message: Call to a member function result_array() on boolean
This error is the category of
Codeigniter Fatal error:
Fatal error : if the table is empty,2 Answers.
1-You should be checking to see if the query worked/has any rows before trying to get its results.
2-You should be checking to see if the query worked/has any rows before trying to get its results. If the table is empty, then the query won't do anything.
I have also face this issue when passing non-existing column name in my get_where() query().
In Code:-
<?php $teachers = $this->db->get_where('teachers',
array('is_deleted'=>0))->result_array();
foreach ($teachers as $row){
$count=$count+1;}
echo $count;
?>
Note:-
Like in code example make sure that the column name is_deleted which use provided to fetch data through get_where() also exit in table of your db.

wasRecentlyCreated and wasChanged are not working

I am trying to use wasChanged and wasRecentlyCreated of models in laravel project but both of them are false in the below code
$saved=$project->accessInfo()->updateOrCreate(['type'=>$request->type],['value'=>$data]);
dd($project->accessInfo[0]->wasChanged(),$project->accessInfo[0]->wasRecentlyCreated,$project->wasRecentlyCreated,$project->wasChanged());
//here is my relation in Project model
public function accessInfo()
{
return $this->hasMany('Modules\Project\Models\ProjectAccessInfo', 'project_id');
}
also below code returns error
dd($project->accessInfo->wasChanged(),$project->accessInfo()->wasRecentlyCreated)
//No such method or attribute in both cases
//Call to undefined method Illuminate\\Database\\Eloquent\\Relations\\HasMany::wasChanged()
Thanks in advance for your help.
getChanges - Get the attributes that were changed.
getDirty - Get the attributes that have been changed since last sync.
When you want to know if the model has been edited since it was queried from the database, or isn't saved at all, then you use the ->isDirty() function.

Eloquent laravel --> Eager Loading

i have the next structure:
model call content
public function credits(){
return $this->belongsToMany('App\models\Credit');
}
model call Credit
public function content()
{
return $this->belongsToMany('App\models\Content');
}
What i am triying to do is extract all the credits of one content, but selecting only the columns that i want, with the below code:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();
The problem that i have is that when i execute all the code the result is:
[]
but if i do a normal query in mysql i can figure out that for the movie exists credits.
I have extracted this code, from other forums, and stackoverflow post.
There is another easy way to specify columns without using closure:
$credits2 = $this->content::with('credits:credits.id,department,job')
->find($id_content->id);
The problem was that $id_content was a result from a previous query, so if i put $id_content didn't work, for that i have to access to the column.
And the solution is:
$credits2=$this->content::with(array('credits'=>function($query){
$query->select('id','department','job');
}))->where('id',$id_content)->get();

Laravel: Get column value from first() result of relationship query

I'm trying to get a single column value from the first result of a Model's belongsToMany relationship query, as i'm returning the ->first() result of the relationship I was hoping $code->reward->title would work but it doesn't.
I get an Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation error
What I'm trying to do is the get the title of the current reward that is linked to a specific code - the code_reward pivot table has a valid_from and expires_at date as the reward linked to a code will change as time goes by, hence the need to get the currently active reward for that code.
Here's my code:
Model: Code
public function rewards()
{
return $this->belongsToMany('App\Reward')->withPivot('valid_from', 'expires_at')->withTimestamps();
}
public function reward()
{
$now = Carbon::now();
return $this->rewards()
->wherePivot('valid_from', '<', $now)
->wherePivot('expires_at', '>', $now)
->first();
}
Controller: CodeController
public function index()
{
$codes = Code::all();
return view('codes/index')->with('codes', $codes);
}
View: Codes/index
#foreach ($codes as $code)
{{$code->id}}
{{$code->reward->title}}
#endforeach
Any help is really appreciated!
Update
Unfortunately both suggestions below ($code->reward()->title and getRewardAttribute() return an Trying to get property of non-object error.
If I remove ->first() from the Code->reward() method and replace $code->reward->title with $code->reward->first() in the view it echoes out the whole reward model as json, however $code->reward->first()->title still returns the Trying to get property of non-object error
Update 2
If I do {{dd($code->reward->title)}} in the view I get the reward title but if I just do {{$code->reward->title}}, I don't!
AND the $code->reward->title works as expected in a #Show view, so could it be that the collection of codes supplied by the controller's #index method isn't passing the necessary data or not passing it in a necessary format??
SOLVED
The issue was caused by one of the $code->rewards in the foreach loop in the index view returning null! The first one didn't, hence the dd() working but as soon as the loop hit a null it crashed.
Once I wiped and refreshed the db (and made sure my seeds where adding only valid data!) it worked. Doing {{$code->reward ? $code->reward->title : ''}} fixed the issue. Grrr.
Your statement is failing because $code->reward->title tells Laravel that you have defined a relationship on your Code model in a method called reward(). However, your relationship is actually defined in the method rewards(). Instead, reward() is a custom method on the model that you have made up. Calling it as a method and not a relation is the quickest way to get what you want.
{{$code->reward()->title}}
As #andrewtweber points out below, you could also make your custom reward() method into an attribute accessor. To do that, just rename the function to getRewardAttribute() and then you can call it in your view like you originally did.
Alternatively, you could get rid of that reward() method entirely and move all of that logic to the controller, where it probably makes more sense. You'd have to use constrained eager loading to pull that off. So in your controller you'd have something like this:
$codes = App\Code::with(['rewards' => function ($query) {
$query->wherePivot('valid_from', '<', $now)
->wherePivot('expires_at', '>', $now);
])->get();
Of course, this would return all of your filtered codes. This is because you cannot apply a sql limit inside a nested eager relationship as outlined here. So in your view, you would then have to do something like this:
{{$code->rewards->first()->title}}
However, it will be simpler to go with my first solution, so that's entirely up to you.
Try to set this method in Code Model, because query builder treats valid_from and expired_at as string, not date?
public function getDates()
{
return ['valid_from','expired_at'];
}

Categories