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
Related
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');
}
Hey so a bit of an overview of the project i want to do. I want to show the user's teams.
When the user logged in and opened the viewteams page. He must show teams he joined/created. To do so i ve done the below processes...
my ViewTeamController
{
public function index()
{
$user=User::first();
$teams=Team::all();
$user->teams()->attach($teams);
return view('teams.viewteams',compact('teams'));
}
public function store()
{
}
}
my User model
public function teams(){
return $this->belongsToMany(Team::class,'team_user','teams_id','users_id');
}
my Team model
public function users(){
return $this->belongsToMany(User::class,'team_user','teams_id','users_id');
}
my migration of the pivot table
public function up()
{
Schema::create('team_user', function (Blueprint $table) {
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('teams_id');
$table->index('users_id');
$table->index('teams_id');
$table->timestamps();
});
}
web.php routes
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
my viewteams.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($teams as $team)
#foreach($team->users as $user)
{{$user->org_name}}
#endforeach
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
my other controller for Creating a team
<?php
namespace App\Http\Controllers;
use App\Team;
use Illuminate\Http\Request;
class CreateTeamController extends Controller
{
public function index(Request $request)
{
return view('teams.createteams');
}
public function store(Request $request)
{
$team=Team::create($request->all());
return redirect()->route('home');
}
}
all my routes
Route::get('/login', function () {
return view('auth/login');
});
Auth::routes();
Route::get('/viewteams','ViewTeamController#index');
Route::post('/viewteams','ViewTeamController#store');
Route::get('/createteams','CreateTeamController#index');
Route::post('/createteams','CreateTeamController#store') ;
Route::get('/home', 'HomeController#index')->name('home');
To achieve currents users teams, first you should get authenticated user id using Auth facade.
After that you can load joined teams for user, using 'with' method. It loads teams relationships.
ViewTeamController
public function index()
{
$user = User::with('teams')->find(Auth::id());
return view('teams.viewteams',compact('user'))
}
viewteams.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"><h2 style="text-align:center;">Your Teams</h2></div>
<div class="card-body">
#foreach ($user->teams as $team)
{{ $team->name }}
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
You will need to revisit and update the code which stores data to the users table and the teams user. The easiest way to store the data in a way which populates the pivot table is to use the sync() method as described at https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships
I'm making some assumptions about names and relationships, buy you may have something like this:
$user = User::find(2);
$user->teams()->sync([4,5]);
In this case, you would put into the pivot table a record for user_id of 2 and team_id of 4, and a second record for a user_id of 2 and a team_id of 5.
If you want to share more code showing route definitions and controllers for how you are currently handling things, we can help with any more specific implementation questions.
I have 3 tables user table, countries table, personal_details table. The structure is as follows
Users:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('role');
$table->string('email')->unique();
$table->integer('terms');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Countries:
Schema::create('countries', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('countrycode');
$table->string('countryname');
$table->string('code');
$table->string('flag');
$table->timestamps();
});
Personal Details:
Schema::create('personal_details', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('first_name');
$table->string('last_name');
$table->string('sex');
$table->date('date_of_birth');
$table->string('country');
$table->string('freelancer_type');
$table->text('about_me');
$table->timestamps();
});
On the welcome page i need to display users profiles including country and associated flag. here is the code im using
Route
Route::get('/', function () {
$category = \App\Category::all();
$user = \App\User::all()->where('role', '==', 'Freelancer');
$post = \App\Post::paginate(3);
return view('welcome', compact('category', 'user', 'post'));
});
and the View
#foreach($user as $users)
<div class="col-lg-3 md-6 xs-6" style="text-align: center">
<div class="card-deck">
<div class="card shadow p-3 mb-5 bg-white rounded">
<div class="card-body">
<img src="/profile_images/{{$users->profileimage->image}}"
style="width: 100px; height: 100px; border-radius: 50%">
<p><span style="font-weight: 900; color: #009dba">{{$users->personaldetails->first_name}} {{$users->personaldetails->last_name}}</span>
<br/>
<span style="font-size: 11px">
{{$users->expertise->profession}}</span>
</p>
<p style="font-size: 11px">{{$users->personaldetails->country}},
ZAR{{$users->expertise->hourly_rate}}/hr</p>
<hr>
<p style="font-size: 11px">{{str_limit($users->personaldetails->about_me, $limit = 80, $end =
'...')}}</p>
{{$users->personaldetails->country->flag}}
<div style="padding-top: 10px"></div>
<a href="/users/{{$users->id}}">
<button>View Profile</button>
</a>
</div>
</div>
</div>
</div>
#endforeach
I am receiving the error Trying to get property 'flag' of non-object. Please help
In this line {{$users->personaldetails->country->flag}} you are calling for relational data. Your relational data is working in chain. First $user is calling relation of personal_details table. In the personal_details table you have stored user_id so the relationship is working. But when you are chaining countries table using personaldetails there will be no result as no relationship exists. You can see that your countries table holds information of only about country, no id of personal_details is stored as foreign key in your countries table. If you want to retrieve data through relations you must store id of personal_details table as foreign key in countries table. So if you store personal_detail_id in your country table, there should be no problem.
Your countries table should look like the following:
Schema::create('countries', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('personal_detail_id');
$table->string('countrycode');
$table->string('countryname');
$table->string('code');
$table->string('flag');
$table->timestamps();
});
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 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