I have a table called users that stores user information and each user can have multiple business accounts that are stored in separate tables.
Models:
User:
id
name
UserProviderAccount:
id
user_id
bussiness_name
bussiness_tell
bussiness_address
UserCompanyAccount
id
user_id
company_name
company_size
UserInfluencerAccount:
id
user_id
name
website
follower_count
Tables Relations :
User :
public function providers(): HasMany
{
return $this->hasMany(UserProviderAccount::class);
}
public function companies(): HasMany
{
return $this->hasMany(UserCompanyAccount::class);
}
public function influencers(): HasMany
{
return $this->hasMany(UserInfluencerAccount::class);
}
I want to display the user's business accounts of all three types at once.
How do I do this?
You simply need to load and call the relationships as follows:
UserController: sample controller and function
public function show(User $user){
//Here we will load all of the relationships for the specific user
$user->load('providers', 'companies', 'influencers');
//Assign the providers from user->providers
$providers = $user->providers;
//Assign the companies from user->companies
$companies = $user->companies;
//Assign the influencers from user->influencers
$influencers = $user->influencers;
//Send all of the data to the view
return view('users.show', compact('user', 'providers', 'companies', 'influencers'));
}
users.show View: simplified version to show you concept.
<p>{{$user->name}}</p>
<p>The providers:</p>
<ul>
#foreach($providers as $provider)
<li>{{$provider->bussiness_name}}</li>
<li>{{$provider->bussiness_tell}}</li>
<li>{{$provider->bussiness_address}}</li>
#endforeach
</ul>
<p>The companies:</p>
<ul>
#foreach($companies as $company)
<li>{{$company->company_name}}</li>
<li>{{$company->company_size}}</li>
#endforeach
</ul>
<p>The influencers:</p>
<ul>
#foreach($influencers as $influencer)
<li>{{$influencer->name}}</li>
<li>{{$influencer->website}}</li>
<li>{{$influencer->follower_count}}</li>
#endforeach
</ul>
Related
How to convert Database Query Builder to Database Eloquent?
$products = DB::table('carts')
->join('products','.carts.product_id','=','products.id')
->where('carts.user_id',$userID) ->select('products.*')
->get();
As you've provided very little information to assist you with, some assumptions are going to be made such as naming conventions and relationship types.
Product.php
Add a carts relationship to your Product model. This assumes a Product can belong to many Carts.
public function carts()
{
return $this->belongsToMany(Cart::class);
}
Cart.php
Add a products relationship to your Cart model. This assumes a Cart can have many Products.
public function products()
{
return $this->belongsToMany(Product::class);
}
Create a pivot table which will maintain the relationships between Carts and Products:
php artisan make:migration create_cart_product_table
Then add your relationship foreign keys to the migration:
public function up()
{
Schema::create('cart_product', function (Blueprint $table) {
$table->id();
$table->foreignId('cart_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->timestamps();
});
}
To add Products to a Cart, you can use the attach or sync methods, for example:
$products = Product::inRandomOrder()->take(5)->pluck('id');
Cart::create(['user_id' => 1])->products()->attach($products);
The above will get 5 Products (at random) from your products table, then create a new Cart with the given user id and attach those Products to the Cart.
To retrieve a Cart and it's associated Products, you would do the following:
$cart = Cart::where('id', $id)->with('products');
The $cart variable can be passed to a view or in a json response where after you can iterate over the Products in the Cart.
$cart = Cart::where('id', $id)->with('products');
return view('cart', compact('cart'));
blade view
<ul>
#foreach ($cart->products as $product)
<li>{{ $product->name }}</li>
#endforeach
</ul>
If you want to get all the Cart records for a given User, you would do the following:
$carts = Cart::where('user_id', $id)->with('products')->get();
return view('carts', compact('carts'));
blade view
#foreach ($carts as $cart)
{{ $cart->id }}
<ul>
#foreach ($cart->products as $product)
<li>{{ $product->name }}</li>
#endforeach
</ul>
<hr />
#endforeach
Or something to that effect.
I have a table called users with a column username. Another table called students with a column code. I have made a hasMany relationship in User model like below and it's working fine.
public function students()
{
return $this->hasMany(Student::class,'code','username');
}
I have another table called institutes where a column is similar to students table named inst. I need to show data from institutes table while showing data of an user. How to make this relationship?
users table
username|mobile|address|password
students table
username|name|inst|roll|reg
institutes table
name|inst|address|phone
This is my home controller
public function index()
{
$admins = User::where('username','=',Auth::user()->username)->get();
return view('home', compact('admins'));
}
And this is my view
#foreach($admins as $key => $admin)
#foreach($admin->students as $student)
{{ $student->reg }}
#endforeach
#endforeach
Add migration to your Students table :
$table->unsignedBigInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');
Update your model User on students method :
return $this->hasMany(Student::class);
Add "with method"
$admins = User::where('username','=',Auth::user()->username)->with('students')->get();
I have 2 tables which are user and customer, The first table has the following fields: (id, name, email, password)
Then, the table customer has the following fields: (id, name, firstname).
In my Controller Customer, via my function index(), I have to retrieve id_user from my table user.
Question 1: Is my relationship correct between my 2 tables?
Model Customer
protected $fillable = ['name', 'firstname', 'user_id'];
public function user()
{
return $this->belongsTo('App\User');
}
Model User
public function customers()
{
return $this->hasOne('App\Customer');
}
Question 2: How do I retrieve ID of the user who is connected ?
I have for now this only...
public function index()
{
$customers = Customer::orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Question 3: I want to understand the two answers, but I would also like to understand how I can adapt my file index.blade.php via my loop, please.
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
Thank you for your explanations.
Your models are good. If you want to return user relation for every customer you should try like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
And in your view you should have:
#foreach($customers as $customer)
<tr>
<td> {{$customer->name}}</td>
<td> {{$customer->firstname}}</td>
<td> {{$customer->user->id}}</td>
More about that here.
Question 1: Is my relationship correct between my 2 tables?
Yes, your relationship is correct.
Explanation:
For your customer table, you indicate that a customer profile belongs to one and only one user. This is an inverse one-to-one entity relationship.
For your user table, you indicate that a user has one and only one customer profile. This is a one-to-one entity relationship.
Question 2: How do I retrieve ID of the user who is connected?
Use Laravel's Eager Loading by calling the with() method to retrieve the customer data with the associated user data like this:
public function index()
{
$customers = Customer::with('user')->orderby('id', 'desc')->paginate(5);
return view('customers.index', compact('customers'));
}
Explanation:
The returned result can be visualized like this:
{Customer}
|
•id
•name
•firstname
•{user}
|
• id
• name
• email
Finally you can get the results including the user ID in your view like this:
#foreach($customers as $customer)
<tr>
<td>{{ $customer->user->id }}</td>
<td>{{ $customer->firstname }}</td>
<td>{{ $customer->name }</td>
</tr>
#endforeach
For more details on Laravel Entity Relationships see the relevant Laravel documentation.
In a Laravel 5 app, I have 5 tables - users, books, authors, followers and activity_feeds.
Users can follow authors and a book can have several authors.
When a book is made, an activity_feeds entry is made that references the book_id.
I need to build an eloquent query to get a collection of activity_feeds for each users, to iterate over in their home page activity feed.
My Book model includes
public function authors()
{
return $this->belongsToMany('App\Author')->withTimestamps();
}
The activity_stream table looks like this (with example data)
id (1)
user_id (3)
type (New Book)
book_id (18)
created_at etc
and my User controller includes
public function feedItems()
{
return $this->hasMany('App\ActivityFeed');
}
public function userFollowings()
{
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'subject_id')->withTimestamps();
}
public function authorFollowings()
{
return $this->belongsToMany('App\Author', 'followers', 'follower_id', 'author_id')->withTimestamps();
}
My current query (which isn't working), contained in the User model is
public function getactivityFeedsAttribute()
{
$userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
$authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
$userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
->orwhereIn('book_id', function($query){
$query->select('id')
->from(with(new Book)->getTable())
->whereHas->authors()
->whereIn('id', $authorFollowings);
})
->get();
return $userFeeds;
}
$userFollowings and $authorFollowings are working fine.
I'm not sure I'm using the correct syntax for data[book_id] to pluck the book id from the activity_feeds row, and I'm really not sure if I can nest a table look up or use $query like this.
It also seems VERY complicated. Am I might be missing something much more straight forward?
In the blade I am calling like this
#forelse ($user->activityFeeds as $activityFeed)
<div class="row">
<div class="col-2">
{{ $activityFeed->user->firstname }}
</div>
<div class="col-2">
{{ $activityFeed->type }}
</div>
</div>
<hr>
#empty
No activity yet
#endforelse
Which works if I just query 'ActivityFeed::whereIn('user_id', $userFollowings)'
I'll rewrite the query in an answer because comments aren't very legible.
public function getactivityFeedsAttribute()
{
$userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
$authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
$books = Book::whereHas('authors', function ($query) use ($authorFollowings) {
// Have to be explicit about which id we're talking about
// or else it's gonna throw an error because it's ambiguous
$query->whereIn('authors.id', $authorFollowings);
})->pluck('id')->toArray();
$userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
->orwhereIn('book_id', $books)
->get();
return $userFeeds;
}
I have 3 models in my app Users, Sales and Plans, when I render sales for each customer (due to storing) I only get id's for other users and models related to that sale (like account manager, owner, plan), now I'm trying to use those ID's inside blade to get names or other rows based on ID and model. Here is the show function:
public function show($id) {
$user = User::find($id);
$sales = Sale::where('customer_id', '=', $id)->get();
return view('profiles.customer', ['user' => $user, 'sales' => $sales]);
}
And in blade I get all those sales like:
#foreach ($sales as $sale)
<li>
<i class="fa fa-home bg-blue"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> {{$sale->created_at->format('g:ia, M jS Y')}}</span>
<h3 class="timeline-header">{{$user->name}} became a customer</h3>
<div class="timeline-body">
<p>Date: {{$sale->sold_date}}</p>
<p>Price: {{$sale->sale_price}}</p>
</div>
</div>
</li>
#endforeach
So inside each record I have like "account_manager_id", "agent_id", "owner_id", "plan_id".
Currently I have this solved by adding public static function (this is for users, have same function for Plan model as well) in Sale model class:
public static function getUser($id) {
return User::where('id', $id)->first();
}
And I'm using it like this in Blade:
Account manager: {{$sale->getUser($sale->account_mgr_id)->name}}
Is this the safest and best way to do it? Or there is something I'm overlooking here?
You need to add relationships in your Sales Model.
class Sales extends Eloquent {
.....
.....
public function accountManager() {
return $this->hasMany('App\User', 'account_manager_id');
}
public function agents() {
return $this->hasMany('App\User', 'agent_id');
}
public function owner() {
return $this->hasOne('App\User', 'owner_id');
}
}
Now $sales->agents will give you a user with agent_id as id in User table.
Update your hasOne, hasMany relationships as your need. Laravel Documentation.
From your blade template, your access your AccountManager as
#foreach($sales->accountManager as $manager)
Name: {{ $manager->name}}
#endforeach
I think you could use Eloquent relationships. Taking your example, you should define relationship in your User model:
<?php
class User extends Eloquent {
public function sales() {
return $this->hasMany(Sale::class, 'customer_id');
}
}
Then, whenever you need to get sales of that user (entries, that relate via customer_id column), just simply do
<?php
$user = User::find($id);
$sales = $user->sales;
This is very fun when when you have to print out list of users that have sales, for example
<?php
public function showUsersWithSales() {
$users = User::with('sales')->get();
return view('users-with-sales', compact('users'));
}
users-with-sales.blade.php example:
#foreach ($users as $user)
User: {{ $user->name }}<br>
Sales:<br>
#foreach ($user->sales as $sale)
{{ $sale->amount }} {{ $sale->currency }} # {{ $sale->created_at }}<br>
#endforeach
<hr>
#endforeach
It would print all users with their sale amount and currency, followed by date when it was created.
This sample takes into account, that your User model has name attribute and your Sale model has amount, currency, created_at and customer_id fields in your database.
To reverse the action, say you have a sale and want to know who made it, just simply define a relationship!
<?php
class Sale extends Eloquent {
public function customer() {
return $this->belongsTo(User::class, 'customer_id');
}
}
Hope that helps!
Eloquent Relationship is your friend, https://laravel.com/docs/5.2/eloquent-relationships and you can solve your problem easily.
Suggestion is to remove all those function access and control from view and put it somewhere else. This will be good habit for you so you can avoid the infamous fat view.