Laravel Collection Creation and Use - laravel

Hey so im realively new to Laravel and im having trouble getting related data from my database. I currently have a few tables related to an overarching Product Family table. I currently get the Product Family, and im trying to get the product codes of the products within that family. The problem is im only returning a single product and not a collection. I know im not getting the information correctly and im stuck. My controller currently looks like this
public function getProductFamily($id)
{
$productfamily = ProductFamilyModel::where('id', $id)->first();
$productskus = ProductModel::where('product_family_id', $id)->get();
foreach ($productskus as $products){
$products->product_family()->get();
}
return view('product_page', compact('productfamily', 'products'));
}
I have models setup for both
Product Family:
public function product()
{
// return $this->hasMany(ProductModel::class, 'product_family_id');
return $this->hasMany(ProductModel::class, 'product_family_products', 'product_family_id', 'product_guid');
}
Product:
public function product_family()
{
return $this->belongsToMany(ProductFamilyModel::class, 'product_family_products', 'product_guid', 'product_family_id');
// return $this->belongsTo(ProductFamilyModel::class);
}

Try this:
public function getProductFamily($id)
{
$productfamily = ProductFamilyModel::where('id', $id)->first();
$products = ProductModel::where('product_family_id', $productfamily->id)->get();
return view('product_page', compact('productfamily', 'products'));
}

Related

Why can't laravel/eloquent find certain table?

I'm trying to fetch some data from a table called "category", but laravel is throwing the
"SQLSTATE[42S02]: Base table or view not found" error.
I've tried with other table names like "company" and it works perfectly. Both of these tables exist but one of them can not be found with the same code.
This throws the error:
public static function getCategories()
{
$categories = [];
$cat = DB::table('category')->get();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
This works as expected (same code except for the table name string):
public static function getCategories()
{
$categories = [];
$cat = DB::table('company')->get(); //table name changed
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
The only difference between those two tables is table collation:
company: utf8_general_ci
category: utf8mb4_swedish_ci
Create a model if it you don't have one. Add the following into your category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'category';
}
Controller
public static function getCategories()
{
$categories = [];
$cat = Category::all();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
You're currently using Query Builder, try use eloquent way.
Ok, I found out we had two separate database-servers with almost identical data in them. Both had databases and tables with the same names, but one was missing the category table.
Of course I was connected to the wrong server from laravel after all.
TL;DR: Simple user error in configuration.

Laravel 5.7 query with 3 tables

I'm pretty new to Laravel and i got stuck with building a more complex query:
I've 3 tables with their models:
Codes:
id
description
factor
public function purposes() {
return $this->hasMany('App\Purpose', 'code_purposes', 'code_id', 'purpose_id');
//I could be wrong here
}
Purpose:
id
name
description
Code_purposes:
code_id
purpose_id
public function codes() {
$this->belongsToMany('App\Code'); //I could be wrong here
}
public function purposes() {
$this->belongsToMany('App\Purpose'); //I could be wrong here
}
What I want is to fetch all the codes with the condition where the purposes name = 'some_name'
I thought this would be easy with the relationships, but I can't figure it out.
So how do I do this in Laravel?
In Code model:
public function purposes() {
return $this->belongsToMany('App\Purpose');
}
In Purpose model:
public function codes() {
return $this->belongsToMany('App\Code');
}
Now you can get data like:
$codes = Purpose::where('name', 'some_name')->first()->codes;
Relation table name must be code_purpose. And no need any model for this table.
Source: Laravel Many To Many Relationships

Laravel Eloquent get all categories of restaurants?

I'm trying to get all categories of restaurants.
My models:
Restaurant
public function categories()
{
return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id');
}
Category
public function restaurants()
{
return $this->belongsToMany(Restaurant::class,'restaurant_categories_relation', 'category_id');
}
In my controller:
$restaurants = Restaurant::where('district_id', $request->district)->paginate(8);
$categories = $restaurants-> ????;
Please help me do this, thanks!
You could use has() like :
Category::has('restaurants')->get();
That will return the categories who are related with the restaurants.
Try also the use of whereHas like :
$users = Category::whereHas('restaurants', function($q){
$q->->where('district_id', $request->district)->paginate(8);
})->get();
Since you've already a Collection we can't query the categories so I suggest adding a function to scope that inside the Restaurant model like :
public static function getCategoriesOfRestaurants($restaurants)
$categories = [];
foreach($restaurants as $restaurant){
array_push( $categories, $restaurant->categories->pluck('id')->toArray());
}
return Category::WhereIn('id', array_unique($categories))->get();
}
Then just call it when you get the $restaurants collection :
$restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
$categories = Restaurant::getCategoriesOfRestaurants($restaurants);
Note: The use of with("categories") when getting the collection will query All the related categories in the first query so the foreach loop will not generate any extra query just looping through the already fetched data, and finally we will get the collection of categories in the return statement.
use with() method for eagerloading, that provides you get all categories in a single query
$restaurants = Restaurant::with("categories")->where('district_id', $request->district)->paginate(8);
foreach($restaurants as $restaurant){
foreach($restaurant->categories as $category)
{{$category}}
}
}
if you want to use categories outside of the loop, then assign these categories to a variable
foreach($restaurants as $restaurant){
$categories = $restaurant->categories;
}
// do something with $categories
Your relation should be
Restruant.php
public function categories() {
return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id','category_id');
}
then in you controller method just wirte
$restruants = Restruant::with('categories')->get();
It should return you collection of all restruants with all related categories.

Search with Relationship - Laravel 5.3

Im making a search functionality where users can type in a name. This is the query im doing:
public function api(Request $request)
{
$query = request()->get('query');
$results = Listing::searchAndCache($query);
return $results;
}
Which hits this:
public static function searchAndCache($query)
{
return self::where('name','like','%'.$query.'%')->where('live',true)->paginate(15);
}
I also need to search 'location' along with this query, the problem is its in a diffrent table. The models name is Location. My question is how would I attach the model Location to this query?
So ideally, I would want to do this for the query:
public static function searchAndCache($query)
{
return self::where('name','like','%'.$query.'%')->where('region','like','%'.$query.'%')->where('live',true)->paginate(15);
}
For search you can use searchable trait. so you can do this :
Listing::where('live',true)->search($query)->paginate(15);
if there is a relation between Listing And Location, you can use Laravel realations to do something like this
Listing::where('live',true)
->search($query)
->location
->search($query2)
->paginate(15);

Laravel 4 Eloquent Two Pivot Table

My tables
Modelos
id
nome slug
marca_id
Pecas
id
codigo
modelo_peca
modelo_id
peca_id
produtos
id
categoria_id
codigo
nome
categorias
id
nome
slug
I have these models
class Modelo extends Eloquent
{
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
class Peca extends Eloquent {
public function modelos()
{
return $this->belongsToMany('Modelo');
}
public function produtos()
{
return $this->belongsToMany('Produto');
}
}
class Produto extends Eloquent {
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
I´m trying to create a route that pass all the products related to a modelo to a view. What´s wrong?
Route::get('/modelo/{slug?}', function($slug = null) {
if ($slug) {
$id = Modelo::where('slug', $slug)->pluck('id');
$pecas = Modelo::find($id)->pecas;
$produtos = Peca::where('id', $pecas)->get();
}
return View::make('produto.home')->with('produtos', $produtos);
Use eager loading
Off the top of my head (also across the language barrier I'll do my best)
You seem to want all Products (produtos) for a specific page category other taxonomy (may be wrong but you can adjust the code as needed)
The where() method expects three parameters iirc so instead the first query would be $id = Modelo::where('slug', '=', $slug)->pluck('id');
The same would apply to the other where statements.
Full query:
if($slug)
{
$query = Modelo::with('pecas.produto')
->where('slug', '=', $slug)
->get();
$produtos = $query->produto;
}
return View::make('produto.home')->with('produtos', $produtos);
Here I've taken a different approach and eager loaded the relations, I'm not 100 percent sure this is how you want this to be done but it hopefully gives you a foundation for using your relations properly in Eloquent.
You don't need to manually get primary keys and perform multiple queries, check out the Eloquent documentation on the Laravel website.

Resources