Laravel Eloquent select from relationship - php

I've been trying to get the hang of Laravel. I'm using Laravel 4.
Right now I have two tables, a 'Products' table and a 'Images' table.
A product can have many images and an image belongs to a product.
So I have two models:
class Product extends Eloquent {
public function images()
{
return $this->hasMany('Image');
}
}
class Image extends Eloquent {
protected $table = 'product_images';
public function product()
{
return $this->belongsTo('Product');
}
}
Now I'm building the 'index' page of a resource, so I do Product::all() in the controller and send this to the view.
In the view I do a foreach and loop over all products. But now I want to get an image to show with the product. But I can't seem to figure out how to get, for instance, the first image.
When I do $product->images I get an object of all images related to the product.
When I do $product->images->url I get an error (Undefined property 'url')
I've tried $product->images->first()->url this also gives an error (Trying to get property of non-object)
What am I doing wrong?

Have you tried eager-loading?
foreach (Product::with('images')->get() as $product)
{
echo $product->images->first()->url;
}

The images property is an array-like property that you can loop through.
foreach ($product->images as $image) {
echo $image->url;
}
Alternatively, if you only wanted the first, you can access the index.
$product->images[0]->url;

You can try using the following PHP function.
$first_image = array_shift($product->images);
Then, $first_image will be one image object, and accessing the URL of the image should be easy: $first_image->ulr
Note: Haven't tested it, but should work. Let us know.

Related

Laravel : Accessing attributes of an Eloquent object results in 'Trying to get property of non-object' error

In my Controller function I am calling the following code:
$ad = Ad::activeRegular()->with('category', 'city')->limit($limit_regular_ads)->orderBy('id', 'desc')->get();
and it successfully returns an Ad Eloquent model object. This object has a relation defined in Ad.php as follows:
class Ad extends Model
{
public function category(){
return $this->belongsTo(Category::class, 'category_id');
}
}
Now the problem
But in my view when I try to fetch the Category of this Ad(vertisement) with the following code:
foreach($ad as $rad){
var_dump($rad->category->category_name)
}
it fires
Trying to get property of non-object
For information, var_dump($rad->category) successfully prints the contents of the related Category object.
Why can't I access the attributes of the object this way.
even $rad->category()->category_name throws the same error.
This happens because one of the ads doesn't have a category.
You can use optional() helper you if want to show name only if ad has a category:
foreach ($ad as $rad) {
var_dump(optional($rad->category)->category_name)
}
Or make sure all ads have a category.

How to use eloquent one to one with all and get laravel

Here is the code for my categories controller
public function index () {
$categories = Category::get(['id', 'image_id', 'name','slug', 'is_active'])->all();
return view('admin_pages.categories.categories', compact('categories'));
}
I want to get image path from the categories_images table using image_id field. I have used the relationship in the categories model as this
public function image () {
return $this->hasOne('App\CategoryImage');
}
On the CategoryImage model i have no relationship specified. How can i get the image path in the categories object.
Thanks in Advance.
You don't need to use all() here. To load relation use with():
$categories = Category::with('image')->get();
To access image you should itarate over collection of categories and then use ->image relation:
$category->image->url;

Laravel Relationship working, but showing it -> Trying to get property of non object

In my Controller I have:
public function showMainPage()
{
$categories = Category::with('subcategories.products.prices', 'subcategories.products.image')->get();
$data = array(
"categories" => $categories,
);
return view('index')->with($data);
}
When I reference this in my view like this:
#foreach($subcategory->products as $product)
<img src="{{ $product->image->thumbnail }}" alt="">
I get a Trying to get property of non-object error.
This is my relationship:
Product.php
public function image()
{
return $this->belongsTo('App\ProductImage');
}
This is my ProductImage Relationship:
public function product()
{
return $this->belongsTo('App\Product');
}
What is wrong there?
As per your question, You joined two table with relationship. When you fetch data from categories table it will return categories and product data.
As per given link by you: http://pastebin.com/U3FAtcsK, your $data variable contain this type of hierarchy.
category
subcategories
products
prices
image
you are trying to display data of image array.
you have to fetch image data like this.
$categories->subcategories->product->image->thumbnail
Understand your Array Hierarchy. You didn't nothing wrong. :)

Laravel accessors appends to all results

I have a table field:
products
-title:New Product
-stock:9
-slug:new-product
And I want is get the additional data 'is_in_stock'. The result will be:
products
-title:New Product
-stock:9
-slug:new-product
-is_in_stock:true
for single data, I can modify the result on the controller itself, but I get stack when getting it to multiple data results. exp. Product::all();
I have read about Eloquent Mutators and Accessors. I have tried the logic on Model files. But I didn't know how to get the result.
This is my Product Model code:
class Product extends Model
{
protected $appends = ['is_in_stock'];
public function getIsInStockAttribute()
{
return $this->attributes['is_in_stock'] = false; // this will be boolean(true/false) result based on the current stock
}
}
Please help for any clue or reference for me to learn.
Thank you in advance :)
Finally I found the reference on http://laraveldaily.com/why-use-appends-with-accessors-in-eloquent/
So I change my Product Model Code to:
public function getIsInStockAttribute()
{
return ($this->stock > 0) ? true : false;
}

Laravel get data from many to many relation

For a school project, I'm creating a website in the Laravel framework.
I can't work with the data from a many-to-many table in my controller.
Here are my models:
class Item extends Eloquent {
public function Tags()
{
return $this->belongsToMany('Tag', 'items_has_tags', 'items_id', 'tags_id');
}
}
class Tag extends Eloquent {
public function LearningMaterials()
{
return $this->belongsToMany('LearningMaterial', 'learning_materials_has_tags', 'tags_id', 'learning_materials_id');
}
}
I want to iterate all tags from my items in my controller:
//get all items
$all = Item::where('public', '1')->get();
foreach($allLm as $item){
$tags = $item->Tags();
var_dump('will iterate');
foreach($tags as $t){
var_dump('will not iterate');
}
}
What is wrong with my code? How can I handle the tags from my items?
FYI: I'm creating a search engine. If the user inserts an input value like "mana", all items with tag "management" should be shown.
Laravel's belongsToMany method queries related models and doesn't get them. That's because you might want to have some additional constraints in your query. What you need to do is:
$tags = $item->Tags()->get();
Or simply:
$tags = $item->Tags;
Calling the relationship function will return a relation object (in this case an instance of BelongsToMany). You can use this to run add further components to your query before running it.
For example:
$only4Tags = $item->Tags()->take(4)->get();
If you want the result of your relation, call get() or simpler, just use the magic property:
$tags = $item->Tags()->get();
$tags = $item->Tags;

Categories