I have some problem to get information about item. I read a lot of information on forums stakoverflow. Maybe i can not find the correct information. Maybe someone knows about that hove to solve the problem
I have 4 tables
public function up()
{
Schema::create('db_items', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_weapons', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('grade_id')->unsigned();
$table->foreign('grade_id')
->references('id')->on('db_item_grades')
->onDelete('cascade');
$table->string('hand')->nullable();
$table->string('name')->nullable();
$table->text('description')->nullable();
$table->string('icon')->nullable();
$table->string('p_atak')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('db_item_db_item_category', function (Blueprint $table) {
$table->increments('id');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')
->references('id')->on('db_items')
->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')
->references('id')->on('db_item_categories')
->onDelete('cascade');
$table->timestamps();
});
}
And 3 models
class DbItem extends Model
{
function weapon()
{
return $this->hasOne(DbItemWeapon::class, 'item_id');
}
function categories()
{
return $this->belongsToMany(DbItemCategory::class,'db_item_db_item_category','item_id','category_id');
}
}
class DbItemWeapon extends Model
{
function DbItem()
{
return $this->belongsTo(DbItem::class);
}
}
class DbItemCategory extends Model
{
function items()
{
return $this->belongsToMany(DbItem::class,'db_item_db_item_category','category_id','item_id')->with('weapon');
}
}
When i try to get some inforamtion it wotrks for example
#foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
#foreach( $category->items as $item)
<p>{{ $item->id }}</p>
#endforeach
</div>
</li>
#endforeach
i got the categories wtith their items and i can view the items id which contains in categoryes but if i want to see more information, its not work
$item->weapon->name
Maybe some of the items does not have a weapon, check for the weapon's existence first:
#foreach($categories as $category)
<li>
<a class="uk-accordion-title" href="#">{{ $category->name }}</a>
<div class="uk-accordion-content">
#foreach( $category->items as $item)
#php
$weapon = $item->weapon;
#endphp
<p>{{ $item->id }}</p>
<p>{{ $weapon ? $weapon->name : null }}</p>
#endforeach
</div>
</li>
#endforeach
Related
when a foreign key value is null I want to return a specific value from the model because when I delete the primary key id row and set a null value on the foreign key shows error. how to can I do it please anybody help me?
Here Is My Country Migration Table:
public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name', 60)->nullable();
$table->string('country_code', 60)->nullable();
$table->string('capital', 120)->nullable();
$table->string('region', 120)->nullable();
$table->string('currency_code', 120)->nullable();
$table->string('currency_name', 120)->nullable();
$table->string('currency_symbol', 120)->nullable();
$table->string('language_code', 120)->nullable();
$table->string('language_name', 120)->nullable();
$table->bigInteger('flag')->unsigned()->nullable();
$table->foreign('flag')->references('id')->on('media_files')->onDelete('cascade')->onUpdate('cascade');
$table->string('dialling_code', 10)->nullable();
$table->integer('status')->default(0)->unsigned();
$table->timestamps();
});
}
Here Is My City migration Table:
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('zipcode')->nullable();
$table->string('order')->default(null)->nullable();
$table->foreignId('country_id')->nullable()->constrained("countries")->cascadeOnUpdate()->nullOnDelete();
$table->timestamps();
});
City Model:
class City extends Model
{
use HasFactory;
public function country(){
return $this->belongsTo(Country::class,'country_id');
}
}
Frontend Blade:
<tbody>
#foreach($CityList as $City)
<tr>
<td><input type="checkbox" name="id[]"></td>
<td>{{$City->id }}</td>
<td>{{$City->name }}</td>
<td>{{$City->zipcode }}</td>
<td>{{$City->country->name }}</td>
<td>{{$City->country->countrycode }}</td>
<td>{{$City->order }}</td>
<td>{{$City->created_at->diffForHumans()}}</td>
<td>
<i class="fa fa-edit" style="font-size: 17px;"></i>
<button href="{{ route('dashboard.city.delete',$City->id) }}" type="button" value="{{ $City->id }}" class="btn btn-danger delete" data-toggle="tooltip" title="Delete">
<i aria-hidden="true" class="fa fa-trash"></i>
</button>
</td>
</tr>
#endforeach
</tbody>
I can suggest a few ways to solve this
First: Make a default value for the relation, like here
public function country()
{
return $this->belongsTo(...)->withDefault(['name' => 'No country']);
}
Second: Make a mutation in City model to find the name of the country
protected function countryName(): Attribute
{
return Attribute::make(
get: fn ($value) => $this->country-> name ?? 'Not country',
);
}
Notes: This way works only for laravel 9.x +, for older versions
please read this article
You can do this: <td>{{$City->country ? $City->country->name : 'No country found'}}</td>
And make sure you are including countries when fetching cities.
Something is wrong with my codes. I knew my concept is right in my own thinking but not working....I want to take out the videos that logged in user liked.
This is my liked table and it stored amv_id and user_id
Schema::create('like_videos', function (Blueprint $table) {
$table->id();
$table->foreignId("amv_id");
$table->foreignId("user_id");
$table->timestamps();
});
This is my amv table and it stored everything of videos
Schema::create('amvs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('desc');
$table->integer('view');
$table->integer('like');
$table->integer('dislike');
$table->integer('category_id');
$table->foreignId('user_id');
$table->string('video');
$table->string('thumb');
$table->timestamps();
});
This is my user table and it stored user infos
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->integer('sub');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('suspend');
$table->rememberToken();
$table->timestamps();
});
This is my controller codes
public function likedvideo() {
$id = auth()->user()->id;
$auth = auth()->user();
$liked = like_video::with('amvs')->where("user_id", "=", $id)->latest();
return view("amvs.likedvideos", [
'liked' => $liked,
'auth' => $auth,
]);
}
I used model relationship on Amv Model
public function amvs() {
return $this->hasMany('App\Models\like_video');
}
This is my view file
#foreach ($liked->amvs as $amv)
<div class="col">
<a href="{{url("amvtube/watch/$amv->id")}}" class="text-decoration-none">
<div class="card mb-2 rounded-0" style="width: 18rem;">
<img src="{{asset('/image/'.$amv->thumb)}}" alt="thumbnail" width="286px" height="161px">
<div class="card-body">
<h5 class="card-title">{{Str::limit($amv->title, 40, '...')}}</h5>
<span class="card-text">{{$amv->user->name}} / Genre: {{$amv->category->name}}</span> <br>
<span class="text-muted">
{{$amv->view}} View {{$amv->created_at->diffForHumans()}}
</span>
</div>
</div>
</a>
</div>
#endforeach
Updated answer:
Add this to your Contoller:
public function likedvideo() {
$id = auth()->user()->id;
$data["auth"] = auth()->user();
$data["liked"] = Amv::with('liked_videos')->where("user_id", "=", $id)->get();
return view("amvs.likedvideos",$data);
}
This to Amv model:
public function liked_videos() {
return $this->hasMany('App\Models\like_video', 'amv_id', 'id');
}
IN VIEW:
var_dump($liked);die();
#foreach ($liked as $amv)
<div class="col">
<a href="{{url("amvtube/watch/$amv->id")}}" class="text-decoration-none">
<div class="card mb-2 rounded-0" style="width: 18rem;">
<img src="{{asset('/image/'.$amv->thumb)}}" alt="thumbnail" width="286px" height="161px">
<div class="card-body">
<h5 class="card-title">{{Str::limit($amv->title, 40, '...')}}</h5>
<span class="card-text">{{$amv->user->name}} / Genre: {{$amv->category->name}}</span> <br>
<span class="text-muted">
{{$amv->view}} View {{$amv->created_at->diffForHumans()}}
</span>
</div>
</div>
</a>
</div>
#endforeach
The foriegn key in your like_videos is wrong.
The format that Laravel looks for by default is table name with id appended.
Schema::create('like_videos', function (Blueprint $table) {
$table->id();
$table->foreignId("amvs_id");
$table->foreignId("user_id");
$table->timestamps();
});
mention the error laravel app is showing?
possible that your users table has id and you're using foreignId('user_id') which model can't find so use same name as id() field with your foreignId() fields or make relations as:
$table->unsignedBigInteger('user_id');
then connect with foreign:
$table->foreign('user_id')->references('id')->on('Users');
MODIFY TABLE SCHEMA LIKE THIS:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->integer('sub');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->integer('suspend');
$table->rememberToken();
$table->timestamps();
});
Schema::create('amvs', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('desc');
$table->integer('view');
$table->integer('like');
$table->integer('dislike');
$table->integer('category_id');
$table->foreignId('user_id')->contrained('users');
$table->string('video');
$table->string('thumb');
$table->timestamps();
});
Schema::create('like_videos', function (Blueprint $table) {
$table->id();
$table->foreignId("amv_id")->constrained('amvs');
$table->foreignId("user_id")->constrained('users');
$table->timestamps();
});``
Look at my codes
products migration
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('short_description')->nullable();
$table->text('description');
$table->decimal('regular_price');
$table->decimal('sale_price')->nullable();
$table->string('SKU');
$table->enum('stock_status', ['instock', 'outofstock']);
$table->boolean('featured')->default(false);
$table->unsignedInteger('quantity')->default(10);
$table->string('image')->nullable();
$table->text('images')->nullable();
$table->timestamps();
});
Schema::create('category_product', function (Blueprint $table) {
$table->bigInteger('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->primary(['category_id', 'product_id']);
});
}
web.php
Route::get('/product/{slug}', DetailsComponent::class)->name('product.details');
DetailsComponent.php
<?php
namespace App\Http\Livewire;
use App\Models\Product;
use Livewire\Component;
class DetailsComponent extends Component
{
public $slug;
public function mount($slug)
{
$this->slug = $slug;
}
public function render()
{
$product = Product::where('slug', $this->slug)->first();
$popular_products = Product::with('categories')->inRandomOrder()->limit(4)->get();
$related_products = Product::with('categories')
->whereHas('categories')
->where('category_id', $product->category_id)
->inRandomOrder()->limit(5)->get();
return view('livewire.details-component', compact('product', 'popular_products', 'related_products'))->layout('Home.master');
}
}
Product.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
details-component.blade.php
#foreach($related_products as $related_product)
<div class="product product-style-2 equal-elem ">
<div class="product-thumnail">
<a href="{{ route('product.details', ['slug' => $popular_product->slug]) }}" title="{{ $related_product->name }}">
<figure><img src="{{ asset('assets/images/products/'.$related_product->image) }}" width="214" height="214" alt="{{ $related_product->name }}"></figure>
</a>
<div class="group-flash">
<span class="flash-item new-label">new</span>
</div>
<div class="wrap-btn">
quick view
</div>
</div>
<div class="product-info">
<span>{{ $related_product->name }}</span>
<div class="wrap-price"><span class="product-price">${{ $related_product->regular_price }}</span></div>
</div>
</div>
#endforeach
I am trying to get specific data from the database by using column category_id when a user clicks a link but I am getting this error:
I am showing categories for a product. I want to create a category manager section i have created the category manager but while i am submitting the form i am getting getting the errors as follows:
Check on this line:
public function render()
{
$product = Product::where('slug', $this->slug)->first();
$popular_products = Product::with('categories')
->inRandomOrder()
->limit(4)
->get();
$related_products = Product::with('categories')
->whereHas('categories', function ($q) use ($product) {
$q->where('category_id', $product->category_id)
})
->inRandomOrder()
->limit(5)
->get();
return view('livewire.details-component', compact('product', 'popular_products', 'related_products'))->layout('Home.master');
}
I am trying to solve a problem, but I don't have so much depth to solve it
I have 2 tables
Book Table
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('about');
$table->text('content');
$table->string('image');
$table->integer('author_id');
$table->timestamps();
});
Authors Table
Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('about');
$table->string('image');
$table->timestamps();
});
I connect both using one-many relationship
My Book.php Model have this
public function authors()
{
return $this->belongsTo(Author::class);
}
My Book.php Model have this
public function books()
{
return $this->hasMany(Book::class);
}
I am able to save the author's id into book table
MY PROBLEM
I want to show the author's name and book name on the front end, so I tried this, but not working
#foreach($books as $book)
<div class="col-md-3">
<div class="home-catalog-image">
<img src="{{ asset('/storage/'.$book->image) }}">
</div>
<p class="author">{{ $book -> author_id }}</p>
<h1 class="book-title">{{ $book -> name }}</h1>
</div>
#endforeach
I am unable to show the author's name with the $book -> author_id, I know this approach is wrong but I don't know what to. Please I need help. Thanks.
Use the relation to show the author name, but more important preload (lazy load) all the Authors before sending $books to the view using with() method
Controller
$books = Books::query()->with('authors')->get(); //or paginate
View
#foreach($books as $book)
<div class="col-md-3">
<div class="home-catalog-image">
<img src="{{ asset('/storage/'.$book->image) }}">
</div>
<p class="author">{{ $book->authors->name }}</p>
<h1 class="book-title">{{ $book -> name }}</h1>
</div>
#endforeach
As i commented, you should rename the relation from authors() to author() since each book has only one author
BelongsTo means that author should be singular
public function author()
{
return $this->belongsTo(Author::class);
}
And in this view
{{ $book->author->name }}
You can see the documentation for the reference.
I listed my category companies and i want to paginate by them. How can i do it?
This is my view:
#foreach ($category->companies as $singleCompany)
<div class="col-sm-12 col-lg-4 col-md-6">
<!-- product card -->
<div class="product-item bg-light">
<div class="card">
<div class="card-body">
<h4 class="card-title">{{$singleCompany->name}}</h4>
#foreach ($singleCompany->categories as $singleCategories)
<ul class="list-inline product-meta">
<li class="list-inline-item">
<i class="fa fa-folder-open-o"></i>{{ $singleCategories->name }}
</li>
</ul>
#endforeach
</div>
</div>
</div>
</div>
#endforeach
My controller looks like this:
$companies = Company::filterByRequest($request)->paginate(9);
$category = Category::find($id);
My category schema:
if(! Schema::hasTable('categories')) {
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('icon')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index(['deleted_at']);
});
My company schema:
if(! Schema::hasTable('companies')) {
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('city_id')->nullable();
$table->string('categories')->nullable();
$table->string('address')->nullable();
$table->text('description')->nullable();
$table->string('logo')->nullable();
$table->timestamps();
$table->softDeletes();
$table->index(['deleted_at']);
});
}
Pivot table for company_category
if(! Schema::hasTable('category_company')) {
Schema::create('category_company', function (Blueprint $table) {
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id', 'fk_p_91029_91033_company__5a12afe2d2772')->references('id')->on('categories')->onDelete('cascade');
$table->integer('company_id')->unsigned()->nullable();
$table->foreign('company_id', 'fk_p_91033_91029_category_5a12afe2d27f0')->references('id')->on('companies')->onDelete('cascade');
});
Can i use somehow $category->companies to paginate my companies? Thank you for help.
Sorry I don't know if $category->companies would be possible in this case.
You might want to try this code.
$companies = Company::leftJoin('category_company', 'companies.id',
'=', 'category_company.company_id')
->where('category_id', $id)
->paginate(9);
This code will left join the table companies and category_company.
It will also be able to get the companies that has the chosen category id.
The result is also ready for pagination in your blade.
If you want pagination for category you have to use paginate() for category.
Try changing your get category query by this
$category = Category::where('unique_id', $id)->paginate(9);
Then you can use {{ $category->render() }} where you need pagination
$category->companies will return an Eloquent collection with all companies and not an instance of LengthAwarePaginator.
$companies will return an instance of LengthAwarePaginator, so iterate over it.
In comments, you've said you want to load companies of specified category. If you've defined the belongsToMany() relationship already, use whereHas() to filter by category:
$companies = Company::filterByRequest($request)
->whereHas('categories', function($q) use($categoryId) {
$q->where('id', $categoryId);
})
->paginate(9);
Then display companies:
#foreach ($companies as $singleCompany)
{{ $singleCompany->name }}
#endforeach
And add pagination links:
{{ $companies->render() }}
https://laravel.com/docs/5.5/pagination