Laravel: check relationship - laravel

Please bear with me, i'm bad at explaining things and i don't think the title suits my problem.
I have a User model and a Course model.
These models have a manytomany relationship.
There currently are 4 Courses, but the User only has a relationship with 2 of them (lets say Course 1 and 3).
On a certain page i'd like to output all Courses, and highlight the Courses the User has a relationship with, so it can view the Course. So, Course 1 and 3 will be highlighted, while Course 2 and 4 will be faded.
User model:
public function courses()
{
return $this->belongsToMany('App\Course');
}
Course Model:
public function users()
{
return $this->belongsToMany('App\User');
}
The Controller
public function index()
{
$member = $this->auth->user();
$courses = $this->courserepository->getAllCourses(); // Course 1,2,3,4
$member_courses = $member->courses; // Course 1,3
// Logic to filter courses which are in a relationship with the User
return view('member.course.index', compact('member', 'courses'));
}
I wish i had some more code, but i have deleted most of it since it was not working as suspected.. I'm looking for someone to point me in the right direction.

In controller replace:
$member = $this->auth->user()->with('courses');
then in view:
<ul>
#foreach($courses as $course)
<li#if(in_array($course['id'], array_column($member['courses'], 'id'))){{' class="highlighted"'}}#endif>
{{$course->name}}
</li>
#endforeach
</ul>

Related

Laravel - Filter records by distinct relation

Right now I have the following models structure,
Country -> State -> City -> Student
And the Student model includes first_name and last_name.
So, I want countries to by filtered by giving student's first name. Like if I give John then I want list of countries which has students whose first name is John.
I was trying something like this,
I added a method called Students() in Country model and returning Student instances from that method. But now I stuck to find out how to filter countries.
Thanks in anticipation.
I came across a similar question recently and I came with the following solution myself. Probably, there are easier ways, but this will get you going for now, I guess.
First we query all the users with first_name == John, as you described, and we limit the query to output only the ID's.
$users = User::where('first_name', 'John')->get()->pluck('id');
We then cross-compare this with the result of Students() from the country model. As I don't know what you're querying for to get the country that you want, I'll just take the Netherlands as an example — that's where I'm from.
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
For this to work, you must make sure that within the Students()-function in your model, the get() is left out.
Final 'result':
$users = User::where('first_name', 'John')->get()->pluck('id');
$users = Country::where('name', 'the Netherlands')->students()->whereIn('id', $users)->get();
in the Student Model create this:
public function city()
{
return $this->belongsTo(City::class,'city_id', 'id');
}
and in the City Model create this:
public function state()
{
return $this->belongsTo(State::class,'state_id', 'id');
}
Finally in the State Model:
public function country()
{
return $this->belongsTo(Country::class,'country_id', 'id');
}
For example if you made things like that in controller:
$students = Student::where('name', 'John')->get();
in the view:
#foreach($students as $student)
$student->city->state->country->country_name;
#endforeach
You can access like that.
If you have setup the model and relationship properly then you need to call them using in with function
$students = Student::where('name','John')->with('city.state.country')->get();
Loop through the $students
#foreach($students as $student)
{{ $student->city->state->country }}
#endif

How my model Laravel could be return me all prices for each item only last date in hasMany?

I have 2 models(market,price_item), i want return last prices for each item (model 2) for 1 market (model 1).
i have in my model 1:
public function prices()
{
return $this->hasMany(MarketPrices::class, self::IDMarket)->groupBy(['item']);
}
This solution give me price for each item but not last price.
I tried orderBydesc but not work.
Thanks you for your help
First of all this is not how you create a relation
A "one-to-many" relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by placing a function on your Eloquent model:
public function prices()
{
return $this->hasMany('Models/MarketPrices', 'id');
}
call it like
$price = Yourmodel::find(1);
dd($price->prices); //return the 1 model connected

Laravel 5.5 Relationships - ErrorException Trying to get property of non-object

Can't display an info from DB to view, have an error
ErrorException
Trying to get property of non-object
Let me explain the logic:
User can create many companies
Companies can have many items
I don't have problems with inserting info to DB, everything is fine.
I can display every info from Users table and Company table in my Show View, but I can't display info from Company_Items tables in my view.
I guess something is wrong with my Relationships or keys, but what?
Trying to display Item name that belong to the specific company
{{$company->company_items->name}}
Company Table:
id(int)
company_name(string)
info(text)
user_id(int)
Company_items Table:
id(int)
company_id(int)
name(string)
Company Model:
class Company extends Model
{
protected $table = 'company';
//relation. MANY companies can be created by ONE user
public function user(){
return $this->belongsTo('App\User');
}
//relation. ONE company can have MANY items
public function item(){
return $this->hasMany('App\Item');
}
}
Item Model:
class Item extends Model
{
protected $table = 'company_items';
//relation. MANY items can be applied TO ONE company
public function company(){
return $this->belongsTo('App\Company');
}
}
Controller:
public function show($id)
{
$company = Company::find($id);
$user = User::find($id);
$company_items = Item::find($id);
return view('company_show')->with(['company' => $company,'company_items' => $company_items]);
}
View:
This is <b>{{$company->company_id}}</b> page info created by <b>{{$company->user->name}}</b><br>
Company category is <b>{{$company->company_category}}</b>.<br>
Item name is <b>{{$company->company_items->name}}</b>. // Can't display this expression
$company->company_items is a list of all the items of the company, you can't call a param on it. And you declared your relation with the name item and not company_items
Try to do :
$company->item[0]->name
or
#foreach($company->item as $item)
{{ $item->name }}
#endforeach
First error you made is:
$company_items = Item::find($id);
This will return the company Item that has the ID=$id which means it will return the Item that has the same ID as the company! I'm sure that's not what you want.
Instead you can do:
$company_items = $company->item;
which will return all the items of that company
and in your view you can access the items with a foreach loop:
#foreach($company_items as $item){
{{$item->name}}
}

Laravel 5 has one relationship

I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields id and name.
What relationship should I use to get the drugs records including the name of the formulation.
Note that 1 drug record has only one 1 formulation record.
I have tried using hasOne relashionship but doesn't work:
My view looks as follows:
#foreach($drugs as $drug)
<li>
<a class="padded-list" href="">{{$drug->name}} ({{$drug->formulation->name}})</a>
</li>
#endforeach
My model relationship in the the Drug model looks as follows:
public function formulation()
{
return $this->hasOne('App\Formulation');
}
Your formulation() method in your Drug model should be:
public function formulation()
{
return $this->belongsTo('App\Formulation');
}
If you call $drug->formulation return Eloquent Collection, you can't get name
You should call $drug->formulation()->first()->name
Good day, formulation() in Drug model shoud be
public function formulation()
{
return $this->belongsTo('App\Formulation');
}
If one formulation can have many drugs, Drugs() in Formulation model shoud be
public function drugs()
{
return $this->HasMany('App\Drug');
}
You can get formulation by this way
$drug->formulation()->first()->name
or
$drug?->formulation?->name
in new php versions

Laravel - Backpack. Display field from other model

After many research I couldn't find the answer to my question.
I have a model "Station" with two fields : "name" and "city_id".
In my Station view (in the backpack admin panel) I would like to display city's name (in the model City).
Station and City model are correctly link with hasMany() and belongTo() methods.
How can I set my column in my crud controller to display the name instead of the city id ?
Thank for your help !
Station Model
<?php
[...] // Namespaces
Class Station {
[...]
public function city() {
$this->belongsTo('App\City');
}
}
City Model
<?php
[...] // Namespaces
class City {
[...]
public function station() {
$this->hasMany('App\Station');
}
}
Crud Controller
<?php
[...] // Namespaces
class CrudController {
public function sampleFunction() {
$stations = App\Station::with('city')->all();
return view('stations', compact('stations'));
}
}
View
Now you can loop the stations on your view like
<ul>
#foreach($stations as $station)
<li>{{ $station->city->name }}</li>
#endforeach
</ul>
You had wrong sight on backpack fields.
Take a look at here.
You can build a custom view and use this for your other model.
Can't add field from different table in laravel-backpack CRUD

Resources