Laravel array shows as null before data array - laravel

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();

Related

How to get all data except last query?

I have this foreach I need to get all data except last one that I current add it
my foreach :
#foreach ($user->projects->sortByDesc('id')->except() as $porject)
// my data
#endforeach
projects is relation between user and projects table
You can use pop() collection method that removes the last item. I would do it in the controller and share the projects with the view.
$projects = $user->projects()->orderBy('id')->get();
$projects->pop();
return view('view', compact('user', 'projects'))
Going from your code you could use take(n):
#foreach ($user->projects->sortByDesc('id')->take($user->projects->count() - 1) as $porject)
// my data
#endforeach
or you could use $loop->last and just render when it's not the last item:
#foreach ($user->projects->sortByDesc('id') as $porject)
#if (! $loop->last)
// my data
#endif
#endforeach
or you could use pop() (as #mrhnn suggested) with tap():
#foreach (tap($user->projects->sortByDesc('id'))->pop() as $porject)
// my data
#endforeach

Passing model object from controller to view which contains inner join in laravel

According to https://laravel.com/docs/5.2/queries#joins documentation, I've done joining in my controller file.
But I want to fetch data from object in my views file. But it shows errors!
My PagesController file
$storages=DB::table('storages')
->join('dealers_of_distributors', 'storages.distributorId', '=', 'dealers_of_distributors.distributorId')
->select('storages.*', 'dealers_of_distributors.dealerId')
->get();
return views('pages.home')->withStorages($storages);
I can not fetch the data from Storages object in my views file
My views file
#if($storages->isEmpty())
<li>No Storage!</li>
#else
#foreach($storages as $stg)
<li>{{ $stg->name }}</li>
<li>{{ $stg->distributor->name }}</li> //I've done implemented distributor() function inside storage moel
#foreach($stg->dealerId as $dealer) //multiple dealers for 1 storage
<li>{{ $dealerId }}</li>
#endforeach
#endforeach
#endif
The first error i'm seeing:
Call to a member function isEmpty() on a non-object
How can i fix it ?
we you use DB::table('table_name')->get(); it will return an array not an object. if you want to have a model object, you should use something like Storage::get();
On Laravel 5.2 and other versions before that, calling get() on QueryBuilder instance will return an array not Collection. That's why your code throwing an error when calling this line:
$storages->isEmpty()
On your code example, $storages is an array thus not having the isEmpty() method. And if you're using QueryBuilder the result will be a flat array, thus cannot query multiple dealers_of_distributors records at a time.
The easiest solution is by using Eloquent.
First you're going to need a Storage model. Within it, add dealersOfDistributors() method to define one-to-many relationship with the dealers_of_distributors table.
<?php
// App/Storage.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Storage extends Model
{
protected $table = 'storages';
public function dealersOfDistributors()
{
return $this->hasMany(DealersOfDistributor::class, 'distributorId', 'distributorId');
}
}
Next you'll also need to have DealersOfDistributor model:
<?php
// App/DealersOfDistributor.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DealersOfDistributor extends Model
{
protected $table = 'dealers_of_distributors';
}
Finally you can easily query the storages table and eager loading its relationship with dealers_of_distributors:
$storages = App\Storage::with('dealersOfDistributors')->get();
return views('pages.home')->withStorages($storages);
And now within your view, you can treat the $storages data as a Collection of Storage model:
#if($storages->isEmpty())
<li>No Storage!</li>
#else
#foreach($storages as $storage)
<li>{{ $storage->name }}</li>
#foreach($storage->dealersOfDistributors as $dealer)
<li>{{ $dealer->dealerId }}</li>
#endforeach
#endforeach
#endif
Hope this help!

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

Retrieving data from belongsToMany relationship in Laravel

I have some problems with getting data from my relationship. I need the tags of some domains.
$domains = Domains::where('customer_id', Auth::user()->customers_id)->get();
There are all the domains I need. On my Domains model I have this belongsToMany relation to my pivot table.
public function tags() {
return $this->belongsToMany('App\Models\Tags_Domains', 'domain_tag', 'domains_id', 'tags_id');
}
I was able to get all the datas from my relation with this:
dd($domains[0]->tags);
That gave me all the data I wanted but only for the very first domain. But I want this for every domain, to pass this new array to my Blade template. I tried many things out but couldn't make it work. ( $collection error, trying to get properly of non-object ... )
Can someone help me there?
Controller Code:
$domains = Domains::where('customer_id', Auth::user()->customers_id)->get();
return view('defaultLayout.domains.tagsdelete', [
'domains' => $domains
]);
This is because you use $domains[0] and you get the first domain.
You must loop through them:
foreach($domains as $domain) {
foreach($domain->tags as $tag) {
var_dump($tag);
}
}
Edit:
If you need the tags in your view here is how:
#foreach($domains as $domain)
<p>{{ $domain->name }}</p> //where name could be any field that $domain has
#foreach($domain->tags as $tag)
<p>{{ $tag->name }}</p> //where name could be any field that $tag has
#endforeach
#endforeach
Glad I was helpful :)

Laravel Return List of Items From Table

Seems like this should be a simple question, but I'm not getting it. I have a table called "following" with columns 'user_id' and 'following_id'. I am trying to return a list of values from the user_id column where the corresponding following_id column contains a certain value (in this case it's 1). See code below.
public function showFollowers()
{
$users = DB::table('following')->where('following_id',1)->lists('user_id');
}
Then, in my view is have
#if (!$user->showFollowers())
You have no followers.
#else
#foreach ($user->showFollowers() as $user)
<p class="username">{{ $user->getUsername() }}</p>
#endforeach
#endif
I'm not getting anything though, and no errors so the query must be correct. I must not be looping correctly in my view...
Thanks!
You are not returning the value of the function. Try:
public function showFollowers()
{
return DB::table('following')->where('following_id',1)->lists('user_id');
}

Resources