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

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;

Related

is there a way to get all related data in laravel connection?

I have two tables named posts and categories. these two tables have one-to-many relationship and I wrote them in models like this:
class Post extends Model
{
...
public function category()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
...
}
class Category extends Model
{
...
public function posts()
{
return $this->hasMany(Post::class, 'category_id', 'id');
}
...
}
This is work fine when I use $post = Post::find($id) in controller and retrieve one post and use $post->category to get category of this post. but what if I want to retrieve all posts and their categories together?
I mean, let's assume that I have 10 posts in DataBase and I have $posts = Post::get(); to get all posts. now, how I can get categories of each post?
One way is loop! for example:
foreach($posts as $post) {
$post['category'] = $post->category;
}
return response()->json($posts);
Yeah! I want to response in Json and I forgot to say earlier, sorry.
Is there better way to do this? I searched and I got nothing by my search. I'll be appreciated if anyone response to my problem. :)
The easiest way to include categories in each post model with json, is simply including it using with() and it will automatically transform it.
return Post::with('category')->get();
In Laravel you do not have to wrap models or collections in response->json(); it will automatically do that.

how to get desired column from other table

there are two tables products and categories, that I created by PHPMyAdmin.
In the products table, it has a column name prd_category that has the foreign key of table categories named cat_id(primary key of categories table).
i am quite new in laravel
i want return all data from product table with category name(cat_name) from another table
//here is my controller
use App\Models\product;
class items extends Controller
{
public function sample(){
return product::all();
}
}
//route
Route::get('/',[items::class,'sample']);
//model for products table
class product extends Model
{
use HasFactory;
function category(){
return $this->hasOne('App\Models\category','cat_id','prd_id');
}
}
//model for category
class category extends Model
{
protected $table='categories';
use HasFactory;
}
pls help and thanks in advance..
you can use this code:
$products = product::whereHas('category',function($q)use($cat_name){
$q->where('name',$cat_name)
})->get();
or :
$categories = Category::where('name',$cat_name)->get()->pluck('id')->toArray()
$products = product::whereIn('category_id',$categories)->get();
Are you sure that one-to-many relation is correct? If a product can belong to many categories, you need to use many-to-many relations. Furthermore, if something else belongs to categories you should use many-to-many polymorphic relations. But let's go with one-to-many.
First, the relation function in Product.php looks incorrect. I think products should belong to a category.
function category(){
return $this->belongsTo('App\Models\Category','cust_name','name');
}
Then you need to define reverse relation in Category.php
function products(){
return $this->hasMany('App\Models\Product','cust_name','name');
}
When you define the relations properly, all you need yo do is to fetch data in controller:
use App\Models\Category
...
Category::with('products')->get();
you can use relationship with forign key like pro_id
function category(){
return $this->belongsTo('App\Models\Category','pro_id');
}
function products(){
return $this->hasMany('App\Models\Product','id');
}
$cat = Category::with('products')->all();
in Blade :
{{ $cat->products->cat_name; }}

Eloquent: filter only rows which has related “children” rows

I want to filter only those categories which have at least one product. I write Category::with('products')->… but how do I filter out those empty categories? Those with no product?
app\Category.php:
class Category extends Model {
// ...
public function products() {
return $this->hasMany('App\Product');
}
// ...
}
app\Http\Controller\CategoriesController.php:
function getIndex() {
$categories = Category::with('products')->get();
return view('categories.index', compact('categories'));
}
You can use has in it
$users = Category::has('products')->get();
// only Categories that have at least one product are contained in the collection
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
I have found solution..
There’s an app function for that: has().
app\Http\Controller\CategoriesController.php:
function getIndex() {
$categories = Category::with('products')->has('products')->get();
return view('categories.index', compact('categories'));
}

Laravel Eloquent belongsTo filtering elements

To start, my models look something like this:
class Post extends Eloquent {
public function url() {
return $this->belongsTo('Url', 'url_id');
}
}
class Url extends Eloquent {
public function category() {
return $this->belongsTo('Category', 'category_id');
}
}
The relationship that is intended is that a Post has a Url and a Url has a Category, so a Post should implicitly have a Category. I am trying to write an Eloquent query to filter posts by category_id. I have a variable that is being passed into a GET route that represents the category_id and want to filter all posts by the category_id that is passed to that route.
Any help is appreciated.
Thanks in advance.

Laravel 4 Eloquent/Model Relationships

I am setting up several Models an want to know the correct approach to table structure and Model relationships.
Let's assume we have a shop containing products, each with properties size and color.
Table products
id
size_id
color_id
price
Table sizes
id
name
Table colors
id
name
Models
class Product extends Eloquent {
public function size() {
return $this->hasOne('Size', 'id');
}
public function color() {
return $this->hasOne('Color', 'id');
}
}
class Size extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'size_id');
}
}
class Color extends Eloquent {
public function products() {
return $this->belongsTo('Product', 'color_id');
}
}
This way I can easily echo the color/size of a product using {{ Product->size['name'] }}. Also, I want to pass Eloquent the size's foreign key size.id like Product::where('size_id', '5') rather than its name size.name.
Problem: Doing $products = Product::has('size', '=', '5')->get() does not give me any results, yet doing $products = Product::where('size_id', '5')->get() does.
I am pretty confused, what went wrong?
I think that the problem is that your ::has() method is looking for products with exactly 5 different sizes on each specific product, which would assume that you would be using $this->hasMany('Size') in your Product model. Where as the ::where() method is returning results where the size of the product is 5.
In the documentation they use an example of comments. A post will have a list of comments. You can find posts that have at least one comment (ie. Post::has('comments')->get()) or you can find posts that have more than 3 comments (ie. Post::has('comments', '>=', '3')->get()).
http://laravel.com/docs/eloquent#querying-relations

Categories