im trying to get the data linked to my model out of the pivot table (many to many relationship).
i put customers on a many to many relationship with departments.
the migration:
Schema::create('customer_department', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('customer_id');
$table->unsignedBigInteger('department_id');
$table->timestamps();
$table->foreign('customer_id')
->references('id')
->on('customers');
$table->foreign('department_id')
->references('id')
->on('departments');
});
the customer model:
public function department(){
return $this->belongsToMany('App\Department');
}
the department model:
public function customer(){
return $this->belongsToMany('App\Customer');
}
now im trying to print out every department the customer is assigned to in the view. i tried
{{$customer->department}}
or
#foreach($customer->department as $depo)
{{$depo->name}}
#endforeach
or
{{$customer->pivot->department_id}}
...
the controller:
public function show(Customer $customer)
{
return view('/customers/customer', ['customer' => $customer]);
}
however i get several error messages, empty arrays or straightup nothing. what am i doing wrong? what did i forget?
You have to have the model retrieved via the Many to Many relationship for it to have this attached pivot model. $customer would not have this pivot but everything returned from $customer->department would have these pivot models attached:
#foreach ($customer->department as $department)
{{ $department->pivot->department_id }}
#endforeach
Though, in this case you don't need to involve the pivot model since you want information from the Department models:
#foreach ($customer->department as $department)
{{ $department->getKey() }}
{{ $department->name }}
#endforeach
It would be a good idea to name these relationships in the plural since they return many, not in the singular.
Related
I have a Customer model which has many Contacts. I want to create a view / list of contacts which paginated and ordered by the latest Contact.
Customer.php
public function contacts()
{
return $this->hasMany(Contact::class);
}
public function latestContact()
{
return $this->hasOne(Contact::class)->latestOfMany()->withDefault();
}
In the view, I want to show the customers like this:
#foreach ($customers as $customer)
<x-table.row wire:key="row-{{ $customer->id }}">
<x-table.cell>
{{ $customer->last_name }}, {{ $customer->first_name }}
</x-table.cell>
<x-table.cell>
{{ $customer->latestContact->contacted_at }}
</x-table.cell>
</x-table.row>
#endforeach
Table Structure
Schema::create('customers', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('first_name');
$table->string('last_name');
});
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->foreignId('customer_id');
$table->string('type');
$table->string('body');
$table->timestamp('contacted_at');
});
I am struggling to get the correct query for this. Here's my last try which gives me the following error:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'latestContact.contacted_at' in 'order clause'...
return view('livewire.dashboard', [
'customers' => Customer::with('customers.*', 'latestContact.contacted_at')
->join('contacts', 'contacts.customer_id', '=', 'customers.id')
->orderBy('latestContact.contacted_at')
->paginate(25)
]);
Appreciate your support!
I think you should rewrite your query like this
Customer::with(['contacts', 'latestContact'])
->orderBy('latestContact.contacted_at')
->paginate(25)
Updated Answer
$customers= Customer::with(['contacts', 'latestContact'=>function($query){
return $query->orderBy('contacted_at','DESC');
}])->paginate(25);
In Customer model you need to modify relation like below
public function latestContact()
{
return $this->hasOne(Contact::class)->withDefault();
}
latestOfMany Indicate that the relation is the latest single result of a larger one-to-many relationship.
latestOfMany($column = 'id', $relation = null)
I have two tables at db, one of them is named users which simply contains user information of website and the other one is tags which contains some hashtags that users can choose from them.
I also created a table named tag_user that can store the tag_id and user_id like this image:
(just like Stackoverflow that a user can select multiple tags such as php, javascript & etc)
So in order to make this relationship between these two, I added this to User model:
public function tags()
{
return $this->belongsToMany(User::class);
}
And also this one to Tag model:
public function users()
{
return $this->belongsToMany(Tag::class);
}
And here is the select option on blade, and users can select multiple tags from db:
<select class="form-control BSinaBold" name="skills[]" id="skills" multiple>
#foreach(\App\Models\Tag::all() as $tag)
<option value="{{ $tag->id }}" {{ in_array($tag->id , Auth::user()->tags->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $tag->name }}</option>
#endforeach
</select>
Now as soon as I load the blade, I got this as error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbname.user_user' doesn't exist (SQL: select users.*, user_user.user_id as pivot_user_id from users inner join user_user on users.id = user_user.user_id where user_user.user_id = 4)
So what's going wrong here? How can I fix this issue?
I would really appreciate any idea or suggestion from you guys...
And here is also the migration of tags & tag_user table:
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('label');
$table->timestamps();
});
Schema::create('tag_user', function (Blueprint $table) {
$table->unsignedBigInteger('tag_id');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['tag_id','user_id']);
});
}
Thanks in advance.
As #aynber described in the comments:
In User model
public function tags()
{
return $this->belongsToMany(Tag::class);
}
And in Tag model
public function users()
{
return $this->belongsToMany(User::class);
}
I have problem to get name from role_user table for each post. I have ACL, so i have 3 tables - users, roles, role_user.
My code looks like this:
Post model
public function user()
{
return $this->belongsTo(user::class);
}
User model.
public function posts()
{
return $this->hasMany(post::class);
}
Role model.
public function users()
{
return $this->hasmany(user::class);
}
PostController,
return view ('admin.posts',[
'posts' => Post::All()
]);
In blade I echo fx user name by:
#foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>{{$post->category->name}}</td>
**<td>{{$post->user->name}}</td>**
</tr>
#endforeach
But the problem is that i want to echo name of role ( from role_user table) for user who wrote post which i am looping.
update
Ok, i solved issue, but probaly there is a better wat. anyone?
I added to models:
User model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
And changed role model:
public function users()
{
return $this->belongsToMany(user::class);
}
Post controller:
class PostController extends Controller
{
public function index()
{
return view ('admin.posts',[
'posts' => Post::with('user')->get(),
'roleUsers' => User::with('roles')->get()
]);
}
and in blade i am doing
#foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>
<p>
#foreach ($roleUsers as $roleUser)
#foreach($roleUser->roles as $role)
<p>
{{ $role->pivot->user_id === $post->user->id ? "Role: $role->name" : "" }}
</p>
#endforeach
#endforeach
I guess there could be a better solution.
Use withPivot() method on the relation. Instead of fetching it from the pivot attribute, it will be on the model, if fetched through the many to many relation.
public function users()
{
return $this->belongsToMany(user::class)->withPivot();
}
Then i would change the front end logic to something in the style of, assuming that all post would have a user with the given role, else you will need to do an if check.
#foreach ($roleUsers as $roleUser)
{{ $roleUser->roles->where('id', $post->user->id)->first()->name }}
#endforeach
You question has a lot of code, but this is the way i perceive it and hopefully it can get you closer to better understanding of it.
Ok i fix my problem, thank you for your help. I found many post's similar to my so I will show solution.
Realtion's:
User belongTo post.
Roles belongsToMany Users.
Users belongsToMany Roles.
DB structure:
users id|User_name
roles id|name
role_user id|user_id|role_id
And what I tried to achieve is while looping through all Post's in blade to display name of role which belongs to that post and solution is very simple.
#foreach ($posts as $post)
{{$post->user->roles->first()->name}}
#endforeach
I have two Table names are User and Role Table. I have set manyTomany relations between them using pivot table name Role_User in Laravel Eloquent.
Now, I want to show both table data in together a view using Eloquent Relationship.(e.g. I want to show in my view a user from users table contain which role in roles table )
Here, is my eloquent relations.
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function users()
{
return $this->belongsToMany('App\User');
}
My, Eloquent Relationship Query.
$users=User::with('roles')->get();
return view('admin',compact('users'));
I'm try in my View.
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->roles->name}}</td>
<td></td>
</tr>
#endforeach
When you call $user->roles, you get a collection of the roles back. So if you want to display them all in a single string, all you have to do is implode the collection on that string:
<td>{{$user->roles->implode('name', ', ')}}</td>
Your $user->rules is instance of Collection of Role model. You can use one more foreach:
#foreach($users as $user)
//do something with user
#foreach($user->roles as $role)
{{$role->name}}
#endforeach
#endforeach
This will work in Laravel 5.0 and above
If we have two Model User and Mark. Then Inside the User Model make a function for relation with Mark. Example
public function marks()
{
return $this->hasMany('App\Models\Mark');
}
So, If you want to display the User name will all his marks. Then inside the controller perform following way.
public function getUserMarks(){
$result = User::select('email', 'name')->where('email', 'usermail#example.com')->with(['marks'])->get();
return view('welcome', compact('results'));
}
I am trying to order my products by price once the client click order by inside the product page. I keep getting the next error: Undefined index: title (View: C:\xampp\htdocs\eshop\resources\views\content\item.blade.php) .
My 'item.blade.php' is the page that shows the larger size of the product in separate page. I think the issue is inside my controller Item function or im my model getItem function , I might be wrong... would appreciate if you could help me out .Thanks
My Route :
Route::get('shop/{category_url}/sorting-{sort?}', 'ShopController#products');
My view in content.products:
#if($products)
<br><br>
High to low |
Low to high
My item.blade.php:
#extends ('master')
#section('content')
<div class="row">
<div class="col-md-12 text-center">
#if('item')
<h1>{{ $item['title']}}</h1>
<p><img width="500" src="{{ asset ('images/' . $item['image'])}}" </p>
<p>{!! $item['article'] !!}</p>
<p><b>Price on site:</b>{{ $item['price']}}$</p>
<p>
#if(Cart::get($item['id']))
<input disabled="disabled" type="button" value="In Cart!" class="btn btn-success">
#else
<input data-id="{{ $item['id']}}" type="button" value="+ Add to cart" class="btn btn-success add-to-cart">
#endif
Checkout
</p>
#else
<p class="text-center" style="font-size: 18px">No product details ...</p>
#endif
</p>
#endsection
My Controller:
public function products(Request $request, $category_url, $sort= 'ASC'){
Product::getProducts($category_url, self:: $data);
$catsort = Categorie::where('url', '=', $category_url)->first();
$products = Product::where('categorie_id', $catsort->id)->orderBy('price', $sort)->get();
return view('content.products', self::$data ,['products' => $products, 'sort' => $sort]);
}
public function item($category_url, $product_url){
Product::getItem($product_url, self::$data);
return view('content.item', self::$data);
}
My Model:
static public function getProducts($category_url, &$data){
$data['products']=$data['category']=[];
if ($category=Categorie::where('url','=', $category_url)->first()){
$category= $category->toArray();
$data['category']=$category;
$data['title']=$data['title']. ' | ' . $category['title'];
if ($products=Categorie::find( $category['id'])->products){
$data['products']= $products->toArray();
}
}
}
static public function getItem($product_url, &$data) {
$data['item'] = [];
if ($product = Product::where('url', '=', $product_url)->first()) {
$product = $product->toArray();
$data['item'] = $product;
$data['title'] .= '|' . $product['title'];
}
}
So based on the chat, I'm going to try and provide an answer.
To start, we need to understand how you want to structure your database.
I can see for sure you have Products & Categories. I'm still not clear what you're trying to achieve with the $items.
So, starting with this, you have two tables. Lets think this through to determine what relationship they have. To start, ask the question, how many categories can a product have (1 or more than 1)? Most people structure categories so products can have more than one, so in Laravel, this is known as a HasMany relationship. The inverse of this is "how many products can a category have?". The answer, once again in this case, is more than 1. Therefore, instead of a HasMany relationship, this is actually a BelongsToMany relationship. A category can have many products, and a product can have many categories.
Next, you need to create a pivot table. This is a table that will store the ID of the product, and the ID of the category that have a relationship. You might create some migrations that look like this. Each of them should go in it's own migration file in the "up" method.
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug', 100)->index();
$table->integer('price');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug', 100)->index();
$table->timestamps();
});
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->index();
$table->integer('product_id')->index();
$table->timestamps();
});
Next we need to setup the models to accept the relationship. So, in your Product.php class, add the following method.
public function categories(){
return $this->belongsToMany(Category::class);
}
And the inverse of this in the Category.php class.
public function products(){
return $this->belongsToMany(Product::class);
}
Now, you should be able to access your relationships like so
$category = Category::first();
$products = $category->products;
Okay, now lets get this working. Your route looks fine, though I wouldn't add the sort the way you are. You can send this in as GET data like so http://example.com/shop/test-category?sort=ASC
Route::get('shop/{category_url}', 'ShopController#products');
Okay, so now your controller.
public function products(Request $request, $category_url){
$category = Category::with(['products' => function($q){
$q->orderBy('price', request()->get('sort')??"ASC");
}])->whereSlug($category_url)->first(); // Eager load in products
return view('content.products', ['category' => $category]);
}
Lastly, within your blade you can now use object syntax instead of array syntax.
#section('content')
Category Name: {{$category->name}} <br />
#foreach($category->products as $product)
Product Name: {{$product->name}} <br />
Product Price: {{$product->price}} <br />
Product Name: {{$product->name}} <br />
#endforeach
#endsection
Without seeing more, I can't be more specific as I'm not clear on how you're trying to handle your $items. You should set it up in the same way we setup products and categories though. Think about the relationship and determine if it's a "HasMany", "HasOne", or "BelongsToMany".
Also, there are default naming conventions you should try and follow. Your database tables should be lowercase and plural. So the table names should be exactly "products" and "categories". Your models should be singular. "Product" & "Category". No need to name it "Categorie". Then, for all pivot tables, you want to name them like the following "category_product". So singular and alphabetical order with the two tables you are pivoting on. Lastly, in your database, you'll want to make sure your pivot table columns are named "product_id" & "category_id", so the singular version of the database name + "_id".
I hope that's enough to get you going.