How can we use carbon diffforhumans with array - laravel

I am using my user controller to return his liked documents and it is returning in array rather than object so i want to use carbon diffforhumans with my date field how can we use it .Here is my controllers code
public function myfavourites()
{
// echo "This is myfavourites";
$user_id = Auth::user()->id;
// $liked_post = Like::all()->where('user_id', $user_id);
return view('user.myfavourites')->with('likes', Like::where('user_id', $user_id)->orderBy('created_at', 'DESC')->paginate(12));
}
and here is my blade code
<h6 class="text-muted">Published <b>{{ $like->document['created_at']->diffForHumans() }}</b></h6>
here h6 is in foreach loop where i am looping throw the all liked documents by the user.
i have relation with my like model to with my document model
here is my relationship function
public function document()
{
return $this->belongsTo('App\Document');
}
whats the solution of this problem either i have to return likes in object form if yes then how?

You need to use Carbon class to use diffForHumans(),
<h6 class="text-muted">Published <b>{{ \Carbon\Carbon::parse($like->document['created_at'])->diffForHumans() }}</b></h6>
if its an array you'll either need to loop through each item in the array or use a key for single item
#foreach($like->document as $key => $value)
<h6 class="text-muted">Published <b>{{ \Carbon\Carbon::parse($value['created_at'])->diffForHumans() }}</b></h6>
#endforeach
or through single key
<h6 class="text-muted">Published <b>{{ \Carbon\Carbon::parse($like->document[0]['created_at'])->diffForHumans() }}</b></h6>

Related

Laravel array shows as null before data array

I have a user that has many properties. This is user should also be able tp view the offers bet on his properties.
So have the relationship set.
User.php
public function properties(){
return $this->hasMany('App\Property');
}
Property.php
public function offers(){
return $this->hasMany('App\Offer');
}
Then in my controller this is what I have:
public function my_offers(){
$properties = Property::whereUserId(Auth::id())->get();
return view('pages.seller.offers.index', compact('properties'));
}
Then I go to my views like this:
#if($properties)
<ul>
#foreach($properties as $property)
<li>{{$property->offers->offer_message}}</li>
#endforeach
</ul>
#endif
When I view the page I see the below error:
Property [offer_message] does not exist on this collection instance.
But this property exists in my table.
If I change my list item to the one below I can see the array:
<li>{{$property->offers}}</li>
I also see that before and after the array with the data, there are two empty arrays as the image shows below:
Is there anything that I didn't correctly?
If not all the properties have offers, then you should check that before the <li>, besides that, offers is a collection, you need to loop through it, that's why you get the error.
#if($properties)
#php ($i = 1)
<ul>
#foreach($properties as $property)
#if ($property->offers)
#foreach ($property->offers as $offer)
<li>Offer {{ $i++ }}: {{$offer->offer_message}}</li>
#endforeach
#endif
#endforeach
</ul>
#endif
If you want to get only de properties that have offers (Querying Relationship Existence):
$properties = Property::whereUserId(Auth::id())->has('offers')->get();
And you should probably eager load that relationship:
$properties = Property::whereUserId(Auth::id())->has('offers')->with('offers')->get();

accessing collections within collections laravel 5

I have a table of "rosters" that's pretty much strictly foreign keys. It acceses the "schools" table, "courses" table, and "students" table. So essentially, a 'student' takes a 'course' at a 'school'. My RostersController has this
public function show($id)
{
$roster = Roster::where('course_id', $id);
return view('roster')->with('roster', $roster);
}
My Roster Model is:
public function students()
{
return $this->hasMany('App\Student');
}
My student Model is:
public function roster()
{
return $this->belongsTo('App\Roster');
}
my view is this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>{{$child->students->first_name}}</p>
#endforeach
The rosters table just saves the student_id rather than all of the student's data that is already in the 'students' table. So i'm trying to access the students table from this relation but when i run this, it tells me that anything related to the students table is 'not on this collection'. I know that I could do things this way if i was working with a hasOne relationship, but how can i accomplish this with a hasMany to output the students table value in each row?
You should try this
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id);
return view('roster')->with('roster', $roster);
}
Try this
Roster.php
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id)->get(); // load the students
return view('roster')->with('roster', $roster);
}
On the view
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>
<!-- Loop through the stundents since this returns an collection of students and not just one -->
#foreach($child->students as $student)
{{$student->first_name}} <br>
#endforeach
</p>
#endforeach
Check this for more information on eager loading
The $child->students is a collection. So, you need to use another foreach loop inside the first one.
Your code should look like this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
#foreach($child->students as $student)
<p>{{$student->first_name}}</p>
<p>{{$student->age}}</p>
<p>{{$sutdent->another_column_in_students_table}}</p>
#endforeach
<p>{{$child->any_other_column_in_roster_table_if_needed}}</p>
#endforeach
So, your first issue is, that
$roster = Roster::where('course_id', $id);
will just return a QueryBuilder instance, you have to use
$roster = Roster::where('course_id', $id)->get();
then for sure, students is a collection, you have to iterate over it like this:
#foreach ($child->students as $student)
{{ $student->yourProperty}} <br>
#endforeach
Update:
I saw you know already about that when to use get() in query laravel 5

How to pass variable from foreach to view in laravel 5.4?

I want to count each location in my Job table by using location_id in my job table with id in location table. below code, I can count result correctly but I don't know how to pass this variable to the view. Please help?
//my code
public function index(){
$location = Location::all();
$count_location = [];
foreach ($location as $locations){
$count_location = Job::where('location_id', $locations->id)->count();
}
}
Use withCount() and view() to pass location with counted jobs to the view:
public function index(){
return view('view.name', [
'locations' => Location::withCount('jobs')->get()
]);
}
In the view:
#foreach ($locations as $location)
{{ $location->name }} has {{ $location->jobs_count }} jobs
#endforeach
You can return the collection of locations to the view and then loop through each object in the collection like so:
return view('index', [
'locations'=> $locations,
]);
Then in your index.blade.php you can use something like a #foreach or #forelse loop
#foreach ($locations as $location)
{{ $location->id }}
#endfoeach
EDIT
From the looks of it you would be better off defining a relationship between locations and jobs (i.e. a "many to many" or "one to many" relationship). this would allow you to get the counts for jobs at given locations very easily like so:
$location->jobs->count()
Eloquent relationships are explained in the documentation here
https://laravel.com/docs/5.5/eloquent-relationships
It would be more efficient if construct your query to fetch the count of related models instead of looping through all the results.
Have a look at Counting Related Models in the documentations.
For example, to get the count of all jobs related to a location, you could do:
$locations = App\Location::withCount('jobs')->get();
foreach ($locations as $location) {
echo $location->jobs_count;
}
You need to adjust the code according to your models structure.
Do this
public function index(){
$locations = Location::all();
return view('index', compact('locations'));
}
In your Location model make a relationship by adding this
public function jobs(){
return $this->hasMany(Job::class);
}
In your index view do this
#foreach ($locations as $location)
{{$location->jobs->count}}
#endforeach
Please note that Job should be there in your your model

Laravel 5.3 access hasone in elequant from view

I'm trying to access a relations table from a collection of data passed in from the controller. I am able to iterate the collection in my view but I am unable to access the relationship data.
There are 2 tables:
stocks (default model)
stock_datas (has a foreign key stock_id which is already setup)
Controller:
public function getstock() {
return view('vehicles.getstock', ['stock' => \App\Stock::all()]);
}
Model (App\Stock) and then (App\StockData)
// From stock model:
public function stockdata() {
return $this->hasOne('App\StockData');
}
// Stock Data model:
public function stock() {
return $this->belongsTo('App\Stock');
}
View (loop):
#foreach ($stock as $k => $v)
{{ print_r($v->stockdata()->get())->year }}
#endforeach
When I try the query below, I get a
Undefined property: Illuminate\Database\Eloquent\Collection::$year (View: F:\websites\tempsite\resources\views\vehicles\getstock.blade.php)
However, year is a column in the stock_datas table.
I am also able to print_r data from the \App\StockData() table so the reference to the table is correct as doing print_r(\App\StockData::all()) from the controller does return all the rows as expected.
What am I doing wrong?
Since it's one to one relation, you should do it like this:
#foreach ($stock as $v)
{{ $v->stockdata->year }}
#endforeach
First one You have to change {{ print_r($v->stockdata()->get())->year }} this line, remove print_r. Next one in foreach loop you can do something like this
#foreach($stock as $one)
{{ $one->stockadata()->first()->year }}
#endforeach
For better solution you should check if isset $one->stockadata()->first()
and after that call ->year. Finally code should be like this
#foreach($stock as $one)
{{ isset($one->stockadata()->first()) : $one->stockadata()->first()->year : 'Default' }}
#endforeach
When calling get() method on any relationship You will always receive collection, no matter what relationship You have.
There are at least two (2) ways to solve Your problem:
1. $v->stockdata->year
2. $v->stockdata()->first()->year
I would suggest You to use first one, because Your stockdata has 1:1 relationship.
Good luck!
For example:
Stock.php model
class Stock extends Model
{
protected $primaryKey = 'id';
function stockdata() {
return $this->hasOne('App\StockDatas', 'id', 'stock_id');
}
public function getStock(){
return Stock::with('stockdata')->get();
}
}
In contriller
public function getstock(Stock $stock) {
return view('vehicles.getstock', ['stock' => $stock->getStock]);
}
view
#foreach ($stock as $k => $v)
{{ $v->stockdata->year }}
#endforeach

Laravel Eloquent Collection and Query

public function create() {
$user_id = auth()->user()->id;
$makers= Maker::all();
return view('maker.create', compact('makers'));
}
What I wanted to do is how to pass the categories name into the view but the form will accept its id. Please help.
$makers is a collection, so you need to use foreach to iterate:
#foreach ($makers as $maker)
{{ $maker->id }}
#endforeach
Update
If you want to pass it to Form::select, use pluck() method:
$makers = Maker::pluck('name', 'id');
It will generate array, which you can use:
{!! Form::select('selectName', $makers, ....) !!}

Resources