I have the following classes (simplified here) in my Laravel 5.7 model:
VEHICLE.PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Vehicle extends Model
{
public function journeys()
{
return $this->hasMany('App\Journey');
}
}
JOURNEY PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journey extends Model
{
public function vehicle()
{
return $this->belongsTo('App\Vehicle');
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
USER.PHP
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function journeys()
{
return $this->belongsToMany('App\Journey');
}
}
I have an intermediate table (journey_user) between users and journeys (see schema attached).
I can easily get all journeys made by a particular user. But how can I get all vehicles used by a particular user? The standard hasManyThrough method does not appear to work because of the Many to Many relationship between users and journeys.
Thanks for your help!
I haven't tested this out. However, it should be possible to get all vehicles by looping through all the user's journeys, creating an array of vehicles and return this as a collection.
This can be added to your User.php model controller:
/**
* Get all vehicles which user has used
*
*/
public function vehicles()
{
$vehicles = [];
$this->journeys()
->each(function ($journey, $key) use (&$vehicles) {
$vehicles[] = $journey->vehicle;
});
return collect($vehicles);
}
Here, we create an empty array. Then we loop through all the journeys of the users (passing the $vehicles array as a reference to update it).
We use the each() collection method to loop through each journey. We create a new entry to the $vehicles array, adding the vehicle.
Finally, we return all vehicles as a collection.
We can use this in our application like so:
User::find($id)->vehicles();
Note: You could return this as an accessor attribute by changing the function name to setVehiclesAttribute(). This will allow you to access the vehicle field like User::find($id)->vehicle.
Related
So I have 2 tables, articles and sub_categories. They are linked throug Eloquent: articles has many sub_categories's, and sub_categories belongsTo article. They are linked with foreign keys as such: in "article" categorie_id.
How do I retrieve the entire table data article where categorie is "DOG" for exemple
Sorry for the abstraction, but this is the best way I can explain it? :D
article model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Articles extends Model
{
use SoftDeletes;
public function user() {
return $this->belongsTo('App\User') ;
}
public function sous_categories() {
return $this->belongsTo('App\SouCategories') ;
}
}
sub_categorie model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SouCategories extends Model
{
public function categories() {
return $this->belongsTo('App\Categories') ;
}
public function articles() {
return $this->hasMany('App\Articles','cat_id') ;
}
}
in my controller i am trying to fetch data based on the foreign key on the sub_category and foreach sub category i am creating an a array like the mainslider contain articles that have a certain sub_category
public function index()
{
$infos = Infos::all();
$categories = Categories::all();
$articles=Articles::all();
$mainslider=Soucategories::with('articles')->get();
foreach($mainslider as $record){
dd($record->articles);
}
die();
return view('frontEnd.homepage',compact('infos','categories','articles','mainslider'));
}
According to the code you have posted it should be something like
Soucategories::where('title', 'DOG')->with('articles')->get();
it seems there will be only on Soucategory with name "DOG", so you can do something like
Soucategories::where('title', 'DOG')->first()->articles
I am pretty new in Laravel and need write a simple backend API.
I am doing smething wrong and I dont know what, because I get some of data from Suppliers table and empty array payments:[ ].
I am trying to get all data from two related tables - PAYMENTS and SUPPLIERS.
It`s a one to many relation SUPPLIERS_ID in PAYMENTS table is connected with ID in SUPPLIERS. Here I give You a graphic representation:
Here`s my code:
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->hasOne('App\Suppliers');
}
}
PaymentsController.php
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class PaymentsController extends Controller
{
public function index()
{
$payments = Suppliers::with('payments')->get();
return response($payments, Response::HTTP_OK);
}
}
And i get the following answear:
[{"id":1,"name":"Ekonaft","adress":"33-100 Tarnow ","email":"ekonaft#gmail.com","payments":[]},
{"id":2,"name":"Orlen","adress":"Ares testowy","email":"email#email.pl","payments":[]}]
What I`m doing wrong that I get te empty array payments:[ ] on the end of each object?
Try the inverse relationship on payments
belongsTo = has a foreign key to another table
Quoting an example
Should i use belongsTo or hasOne in Laravel?
This is how you can access suppliers from Payments
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo('App\Suppliers');
}
}
This is payments from suppliers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany('App\Payments','suppliers_ID','id');
}
}
Also, make sure the id's are visible on the output (if id's are hidden, laravel can't work with the relationship). You can also specify the keys on the relationship if you want to use hasOne
Edit: add the keys names within the relation, your fk naming is in capslock
Change you relations like bel
Suppliers.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
public function payments()
{
return $this->hasMany(App\Payments::class, 'suppliers_ID', 'id');
}
}
Payments.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payments extends Model
{
public function suppliers()
{
return $this->belongsTo(App\Suppliers::class, 'suppliers_ID', 'id');
}
}
then try again..... :)
You are getting empty array of payments:[] due to miss-matching table relationship key name.
Please, make few changes in both relational function.
public function payments()
{
//return $this->hasMany('App\Model', 'foreign_key', 'local_key');
return $this->hasMany('App\Payments', 'suppliers_id');
}
public function suppliers()
{
//return $this->belongsTo('App\Model', 'foreign_key', 'other_key');
return $this->belongsTo('App\Suppliers', 'suppliers_id');
}
You can learn more about eloquent relationship directly from Laravel documentation for better understanding. https://laravel.com/docs/5.7/eloquent-relationships#one-to-many
Let me know if you still getting same error.
Hi Guys I have started building my first project using Laravel,
I have done a crash course on Laracast, learnt hasMany and belongTo however I am stuck at where I have categories which yet don't have any products. I don't have any sub categories I only want to show the categories which has some products and hide the empty one
So far I am getting my categories like this
$stocksCats = stockscat::isLive()->where('status', '=', 1);
my stocks class has looks like this
<?php
namespace App;
//use Illuminate\Database\Eloquent\Model;
class stock extends Model
{
public function scopeisLive($query) // With Scope
{
return $query->get();
}
public function stockcat()
{
return $this->belongsTo(stockscat::class);
}
public function stockgallery()
{
return $this->hasmany(stockgallery::class);
}
}
and my stocks cat class looks like this
<?php
namespace App;
// use Illuminate\Database\Eloquent\Model;
class stockscat extends Model
{
public function scopeisLive($query) // With Scope
{
return $query->get();
}
public function stocks()
{
return $this->hasmany(stock::class);
}
}
Laravel provides a has() method (See docs) to check if an eloquent has a relationship. The following code snippet should be the solution:
$stocksCats = stockscat::isLive()->has('stocks')->where('status', '=', 1);
I am trying to get all rows in a payments table where I have another table called projects I want to get all rows that in payments table where project_id column = ID of the row inside projects table I am using Laravel framework please help me this some the code
Payment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $table = 'payments';
public function projects() {
return $this->belongsTo('App\Project');
}
}
Project Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = "projects";
public function payments() {
return $this->hasMany('App\Payment');
}
}
Route File
Route::get('special/{project_id}', 'SpecialController#index');
The index function in the Controller
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Payment;
use Illuminate\Http\Request;
class SpecialController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Project $project_id)
{
return view('special.index')->with(['projects' => $project_id]);
}
This is my problem please help
All the best 😀
In your controller, I see that u have injected an instance if Project, but named as $project_id. Thats not an id, id would have been resolved to an instance of Project.
public function index(Project $project_id)
just a note. use index method to show the listing, unless its a nested resource.
public function index(Project $project)
{
//assuming that $project is an instance of Project
$project = $project->with('payments')->get();
//$project will now include the related payments as well
//if you want to check do this, for debugging uncomment next line
//dd($project->toArray());
return view('special.index')->with(['project' => $project]);
}
whats happening in code is that $project is retrieved with its related payments. in with('payments') the 'payments' is the name of the relationship.
I have this kind of database design
user_classes
- id
- user_id
- class_schedule_id
class_schedules
- id
- class_id
- date
classes
- id
- name
I am now in my UserClass.php Model File
public function classSchedule() {
return $this->belongsTo('\App\ClassSchedule');
}
public static function getClassByUser($user_id){
$user_class = self::where('user_id','=',$user_id)->with('classSchedule');
//other codes here...
}
My question here is that how can I access the name of the class in the class table since the user_classes table doesn't have a direct access to the class instead it should go through first to the class_schedules table.
I am not sure what Eloquent ORM Relationship should I use.
Your help will be greatly appreciated!
thanks! :)
First of all you will need to rename the third class, from class to something else. Then try this,
class user_classes Extends Eloquent {
function classSchedule() {
return $this->hasMany('Class_schedules','class_schedule_id');
}
}
class class_schedules Extends Eloquent {
function userClasses() {
return $this->belongsTo('user_classes', 'class_schedule_id');
}
function classSomething() {
return $this->hasOne('class_something','id');
}
}
class class_something Extends Eloquent {
function classSchedules() {
return $this->belongsTo('class_schedules', 'id');
}
}
Try and follow the naming conventions within Laravel, that will make your life easier down the road.
It uses the snake_cased version of the plural of your model name to define the table name automagically.
Besides that, when you have a relation with single or plural output, name your relation methods accordingly to describe what they do and what kind of output you can expect.
I prefer a dir /app/Models for the models, hence the namespace, you can change this to /app if that's where your models are.
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserClass extends Model
{
// only defined because laravel auto generates alphabetically
protected $table = 'user_classes';
public function user()
{
// given that User model was moved to app/Models, if not, use \App\User
return $this->belongsTo('\App\Models\User');
}
public function classSchedule()
{
return $this->belongsTo('\App\Models\ClassSchedule');
}
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ClassSchedule extends Model
{
public function class()
{
return $this->belongsTo('\App\Models\Class');
}
}
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Class extends Model
{
public function classSchedules()
{
return $this->hasMany('\App\Models\ClassSchedule');
}
}
Now you can basically fetch all entries of UserClass for a particular user, with or without eager loading...
$userClasses = UserClass::where('user_id', $userId)->get();
$userClasses->map(function($userClass) {
echo $userClass->classSchedule->class;
});
More preferably you'll have a method userClasses() with a hasMany relation in your user model