How do I get related model from collection in Laravel 5.2? - php

I have a method returning all job post data. This is what I have tried:
public function show($id)
{
$applicantData = Applicant::whereId($id)->first();
$jobData = Job::all();
//dd($jobData);
//dd($jobData->job_title);
return view('applicant.confirmation',compact("applicantData","jobData"));
}
dd($jobData); returns:
dd($jobData->job_title); it returns an error:
ErrorException in ApplicantController.php line 150: Undefined
property: Illuminate\Database\Eloquent\Collection::$job_title
How can I get the $jobData->job_title value?

You should iterate collections using the each method in Laravel:
$jobData->each(function ($item, $key) {
dd($item->job_title);
});

public function show($id)
{
$applicantData = Applicant::whereId($id)->first();
$jobData = Job::find($applicantData->job_id); //this will give you the job
dd($jobData);
dd($jobData->job_title);
return view('applicant.confirmation',compact("applicantData","jobData"));
}

You have to loop through $jobData since it will return all rows. Something like:
$jobData = Job::all();
foreach ($jobData as $job) {
echo $job->job_title;
}

They are object in arrays so you can directly pickout the value. If you need first item then $jobData[0]->job_title or $jobData->first()->job_title or you can loop foreach($jobData as $data){$data->job_title}

$jobData is a collection so you cannot directly access job_title like $jobData->job_title. I figure you want to access them in your view file. hence do following
#foreach($jobData as $job)
{{ $job->job_title }}
#endforeach

Related

Undefined array key but with dd() works

I've done a query at Laravel and to check result content, I've used dd, but, for some reason, when I remove the dd(), it throws an exception sayint "Undefined array key 0". However, with dd DO find the key.
Code is this:
public function getFormatosArticulo(Articulo $articulo){
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
dd($formatoRaw[0]);
$formato = $formatoRaw[0];
return $formato;
}
And dd output is this:
I guess you are calling getFormatosArticulo function for multiple times, and passed not exists id into it. The get() function will always return a empty collection even if no data matched.
Can you test your function use code below and check if id does exists or not?
public function getFormatosArticulo(Articulo $articulo){
try {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
$formato = $formatoRaw[0];
return $formato;
catch (Exception $e) {
dd($articulo->id); // i guess there is no articulo_id equal this in formato table.
}
}
The reason this happens is that dd stands for “dump and die” so your first iteration goes through but you don’t check the rest because you use die(). A solution to this can be as simple as:
public function getFormatosArticulo(Articulo $articulo) {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
if ($formatoRaw) {
$formato = $formatoRaw[0];
return $formato;
}
}
Since you are only interested for the [0] position though a similar approach would be:
public function getFormatosArticulo(Articulo $articulo) {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->first();
if ($formatoRaw) {
return $formatoRaw;
}
}

can't orderBy accessor in Laravel

I cant orderBy points. Points is accessor.
Controller:
$volunteers = $this->volunteerFilter();
$volunteers = $volunteers->orderBy('points')->paginate(10);
Volunteers Model:
public function siteActivities()
{
return $this->belongsToMany(VolunteerEvent::class, 'volunteer_event_user', 'volunteer_id', 'volunteer_event_id')
->withPivot('data', 'point', 'point_reason');
}
public function getPointsAttribute(){
$totalPoint = 0;
$volunteerPoints = $this->siteActivities->pluck('pivot.point', 'id')->toArray() ?? [];
foreach ($volunteerPoints as $item) {
$totalPoint += $item;
}
return $totalPoint;
}
But I try to sortyByDesc('points') in view it works but doesn't work true. Because paginate(10) is limit(10). So it doesn't sort for all data, sort only 10 data.
Then I try to use datatable/yajra. It works very well but I have much data. so the problem came out
Error code: Out of Memory
You could aggregate the column directly in the query
$volunteers = $this->volunteerFilter();
$volunteers = $volunteers->selectRaw('SUM(pivot.points) AS points)')->orderByDesc('points')->paginate(10);

Pagination - call to undefined method ::links

I'm trying to paginate data that's returned from a model.
But keep getting an error :
Call to undefined method App\Shortlist::links()
Its on my Shortlist model and the code I'm using the paginate is (Controller)...
public function shortlist()
{
$view_data = array
(
'shortlist' => Shortlist::where('user_id', $this->user_id)->with('property')->orderBy('created_at', 'desc')->paginate(4)
);
$view = 'frontend.'.themeOptions().'.account.shortlist';
// Change View Per Template...
if(view()->exists($view))
{
// Shared View in the Templates...
return view($view, $view_data);
}
else
{
// Load Shared View...
return view('frontend.shared.account.shortlist', $view_data);
}
}
Then in my view, I'm using :
{{ $shortlist->links() }}
But keep getting that error, any help as to why?
Thanks
$shortlist is not defined, you need to return that collection to your view.
You can call ->links() on a collection. $view_data is just an array, you want to access the shortlist collection in that array, so you need to call it like this
{{ $view_data['shortlist']->links() }}
Further why do you create this variable:
$view_data = array
(
'shortlist' => Shortlist::where('user_id', $this->user_id)->with('property')->orderBy('created_at', 'desc')->paginate(4)
);
if you don't use it. If you don't use it I would just declare it like this:
$shortlist = Shortlist::where('user_id', $this->user_id)->with('property')->orderBy('created_at', 'desc')->paginate(4);
and return that to your view, looks cleaner.

Laravel Collection Loop to another Collection

How to loop the eloquent collection from one to another? I'm just getting first line of array. I have more than 4 array in the collection.
$queries = Students::where('year',"=", 1)->get();
$students = new Students();
foreach ($queries as $query) {
$students->name = $query->name;
$students->faculty = $query->faculty ."Add something";
$students->year = $query->year;
}
dd($students);
I want to change the collection a bit before I print to json. For example, I want add something behind the faculty
Use the transform() method to modify collection:
$students = Students::where('year', 1)->get();
$students->transform(function($i) {
$i->faculty = $i->faculty . 'add something';
return $i;
});
You also can use resource classes to transform the data before returning JSON response.
You could use map() to modify collection-
$queries = $queries->map(function($query){
$query->faculty = $query->faculty."kfjhgli";
return $query;
});
return $queries;

How to use get object in controller laravel

I have a function in controller to remove category and its image file. But i am not able to access the path property. I am getting this error Undefined property: Illuminate\Database\Eloquent\Collection::$path. It is returning path but i am unable to use it.
public function remove($id) {
//$category = Category::find($id)->delete();
$category_image = CategoryImage::where('category_id', '=', $id)->get(['path']);
echo $category_image->path;
//return back();
}
You can use first() if you need to get just one object:
$category_image = CategoryImage::where('category_id', '=', $id)->first();
if (!is_null($category_image)) { // Always check if object exists.
echo $category_image->path;
}
When you're using get(), you're getting a collection. In this case you can iterate over the collection and get data from each object, or just use index:
$category_image[0]->path;
You get a collection, you have to loop throug the collection this way:
foreach ($category_image as $image) {
echo $image->path;
}

Categories