Schema::create('discounts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->dateTime('from', $precision =0);
$table->dateTime('to', $precision =0);
$table->enum('status', [0, 1, 2])->default(0)->comment('0:active 1:expired 2:scheduled');
$table->timestamps();
$table->softDeletes();
});
Schema::create('discount_product', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->unsignedBigInteger('discount_id');
$table->unsignedBigInteger('product_id');
$table->foreign('discount_id')->references('id')->on('discounts')->onDelete('cascade');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->float('rate');
$table->timestamps();
$table->softDeletes();
});
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->float('price');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('brand_id');
$table->string('image')->nullable();
$table->text('description')->nullable();
$table->integer('quantity');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
public function discountProducts()
{
return $this->hasMany(DiscountProduct::class);
}
public function discount()
{
return $this->belongsTo(Discount::class);
}
/**
* Get product of discount
*/
public function product()
{
return $this->hasMany(Product::class);
}
I have 3 tables like this : discount, discount_product, product, in my detailProduct.blade.php, I want to get the product have the discount, but I don't know to do that. Can someone help me ? Thanks you very much
This is my : view detail function : I get the discount_products
public function show($id)
{
$discount = $this->discountRepository->getDiscountById($id);
$discount_products = $this->discountRepository->getDiscontProductOnDiscount($id);
return view('user.discounts.detailDiscount',
['discount_products' => $discount_products, 'discount' => $discount]);
}
you can do like this
$data['discount'] = $this->discountRepository->getDiscountById($id);
$data['discount_products'] = $this->discountRepository->getDiscontProductOnDiscount($id);
return view('user.discounts.detailDiscount', $data);
and at your view you can access data like this $discount , $discount_products
if you have many data at your $product, you cant foreach first and print like this at the view, my assumption you will print at table so will like this
<tbody>
#foreach ($products as $row)
<tr>
<td>{{$row->name}}</td>
<td>{{$row->price}}</td>
<tr>
#endforeach
</tbody>
if your data only have 1 row you can access like this
$products[0]->name
Related
I have 3 models:
User
Company
Enquiry
A user can own more than one company, a company can only belong to one user. An enquiry can belong to many companies and a company can have many enquiries.
The migrations look as follows:
User migration
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('contact_number');
$table->longText('address')->nullable();
$table->integer('postal_code');
$table->string('activation_token')->nullable();
$table->boolean('active')->default(false);
$table->enum('type', ['Admin', 'End User', 'Service Provider', 'Broker']);
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Company Migration
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('service_provider_id')->nullable();
$table->unsignedInteger('broker_id');
$table->string('name');
$table->string('email')->unique()->nullable();
$table->string('contact_number');
$table->longText('address')->nullable();
$table->integer('postal_code');
$table->enum('status', ['Confirmed', 'Declined', 'New'])->default('New');
$table->timestamps();
$table->softDeletes();
});
Schema::table('companies', function (Blueprint $table) {
$table->foreign('service_provider_id')->references('id')->on('users');
$table->foreign('broker_id')->references('id')->on('users');
});
Enquiries Migration
Schema::create('enquiries', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('end_user_id');
$table->unsignedInteger('category_id');
$table->string('title');
$table->longText('description');
$table->integer('radius');
$table->enum('status', ['New', 'In Progress', 'Complete'])->default('New');
$table->timestamps();
});
Schema::table('enquiries', function (Blueprint $table) {
$table->foreign('end_user_id')->references('id')->on('users');
$table->foreign('category_id')->references('id')->on('categories');
});
CompanyEnquiry Migration
Schema::create('company_enquiry', function (Blueprint $table) {
$table->integer('company_id')->unsigned()->index();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->integer('enquiry_id')->unsigned()->index();
$table->foreign('enquiry_id')->references('id')->on('enquiries')->onDelete('cascade');
$table->primary(['company_id', 'enquiry_id']);
});
I have set up the various relationships in their respective models.
What I'm trying to achieve is query the database to retrieve only those enquiries which belong to the user via the company.
How can I achieve this?
Something like this (add the real model, relation names ans columns):
$enquiries = Enquiries::whereHas(['companies' => function($query){
$query->whereHas(['user' => function($query){
$query->where('id', $user_id);
}]);
})
->get();
You could do it this way with shorter code.
$enquiries = Enquiries::whereHas('companies.user', function($query) use($user_id){
$query->where('id', $user_id);
})->get();
I am very beginner in Laravel.
I have Laravel 5.8 in my project.
I have this code:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('enable', 1)->default(0);
$table->string('name', 120)->nullable();
$table->string('surname', 120)->nullable();
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
........
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('commentable_type');
$table->bigInteger('commentable_id');
$table->char('enable', 1)->default(0);
$table->char('to_stats', 1)->default(0);
$table->tinyInteger('rating')->default(0); // 1-5
$table->text('content');
$table->dateTime('date_time');
$table->ipAddress('ip');
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
How can I show users list:
sort after number of comments held
sort after number of votes which user has (comments-> rating)?
Try this
//User model
public function comments()
{
return $this->hasMany('App\Comment');
}
public function usersSortedByCommentCount()
{
$users = User::with('comments')->get()->sortBy(function($user)
{
return $user->comments->count();
});
return $users;
}
public function usersSortedByRating()
{
return User::whereHas('comments', function ($q) {
$q->orderBy('rating', 'desc');
})->get();
}
$users_sorted_by_comments = User::with('comments')->get()->sortBy(function($user){
return $user->comments->count();
})
The other condition is quite similar, you need to load ratings on comments and then just sort by that count like this:
$users_sorted_by_ratings_on_comments = User::with('comments')->get()->sortBy(function($user){
return $user->comments->reduce(function($carry, $comment) {
return $carry + $comment->rating;
}, 0 );
})
Laravel Collection reduce
I have a many to many relation
public function products()
{
return $this->belongsToMany(Product::class); // relation between books and categories
}
public function parts()
{
return $this->belongsToMany(Part::class); // relation between books and categories
}
my migrations :
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('link')->default('anohe.com');
$table->string('pname')->default('product');
$table->timestamps();
$table->string('description',3000)->nullable();
$table->string('smalldescription',500)->nullable();
});
}
public function up()
{
Schema::create('parts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function up()
{
Schema::create('part_product', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('product_id');
$table->unsignedInteger('part_id');
$table->timestamps();
$table
->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table
->foreign('part_id')
->references('id')
->on('parts')
->onDelete('cascade');
});
}
How can I get products that have a special part_id?
If your relations are correct, that should work:
$specialPartIds = [1];
$products = Product::whereHas('parts', function ($query) use ($specialPartIds) {
$query->whereIn('id', $specialPartIds);
})->get();
dd($products->toArray());
I have 2 table 1st products belongsToMany Colors and 2nd Colors belongsToMany products
I made my table like this
Product Table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('image');
$table->string('stock');
$table->string('title');
$table->string('slug')->unique();
$table->string('gender');
$table->text('description');
$table->integer('price');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
$table->dateTime('published_at');
});
and Color Table with relationship
Schema::create('colors', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('color_product', function (Blueprint $table) {
$table->integer('color_id')->unsigned()->index();
$table->foreign('color_id')->references('id')->on('colors')
->onDelete('restrict')
->onUpdate('restrict');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')
->onDelete('restrict')
->onUpdate('restrict');
$table->timestamps();
});
I am trying to add more color in in 1 product like this
public function addproductdetailspost(Request $request, $product){
$product = product::where('slug', $product)->firstorfail();
$color = color::where('name', $request->color)->firstOrCreate();
$color->name = $request->color;
$color->save();
$product_id = $product->id;
$color_id = $color->id;
$product->colors()->attach($product_id);
return Redirect::back()->with('status', 'Post Success');
}
It's not working, I am getting this error
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::firstOrNew(), 0 passed in C:\xampp\htdocs\swimwear2\app\Http\Controllers\AdminController.php on line 109 and at least 1 expected
It's the wrong direction.
$color->products()->attach($product_id);
I'm trying to get the users that are on today's shift. I have a many to many relationship between the User and Shift model with a pivot table called user_shifts.
My User model:
/**
* Get the users shifts
*/
public function shift()
{
return $this->belongsToMany('App\Shift', 'user_shifts', 'user_id', 'shift_id');
}
My Shift model
/**
* The shift can have many users
*/
public function users()
{
return $this->belongsToMany('App\User', 'user_shifts', 'shift_id', 'user_id')->withPivot('start_time', 'end_time');;
}
In my controller I thought I could do something like:
$shift = Shift::all()->where('date', date('Y-m-d'));
$users = User::all()->where('shift_id', $shift);
return $users;
But that is returning null. Any help would be appreciated!
If it matters my db schema is:
Schema::create('shifts', function (Blueprint $table) {
$table->increments('id');
$table->date('date');
$table->boolean('weekend');
});
Schema::create('user_shifts', function (Blueprint $table) {
$table->increments('id');
$table->integer('shift_id');
$table->integer('user_id');
$table->time('start_time');
$table->time('end_time');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('fname');
$table->string('lname');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});