Sorting userlist in Laravel - php

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

Related

Get the value from 2 table on laravel

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

Login in Laravel 5.8

I am beginner in Laravel. I use in my project Laravel 5.8.
I use Laravel login system in my project.
I have my user migration:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->char('enable', 1)->default(0);
$table->char('demo_mode', 1)->default(0);
$table->date('account_paid_for');
$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->string('url_address', 160);
$table->text('content')->nullable();
$table->dateTime('last_activity')->nullable();
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
I need to change Laravel's default login to verify that enable = 1
Only users with enable = 1 can log in. How to do it
You can add an after middleware or just override the authenticated method within your LoginController:
use Auth; // add this at the top
protected function authenticated( Request $request, $user )
{
if( ! $user->enable) {
Auth::logout(); // log out the user
return back()->with('error', 'The user is not allowed to enter');
}
return redirect($this->redirectTo);
}

Displaying a list of users with information on the number of votes in Laravel

I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->char('enable', 1)->default(0);
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
....
$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);
$table->text('content');
$table->dateTime('date_time');
$table->ipAddress('ip');
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_unicode_ci';
});
User.php:
public function userCommentsCount()
{
return $this->hasMany('App\Comment', 'commentable_id', 'id')->where('enable', '=', '1')->where('to_stats', '=', '0');
}
I get my user list from this code:
$users = User::ofRoleType($role)->withCount('commentsReceived')->paginate(50);
#foreach ($users as $user)
User id: $user->id <br/>
#endif
I need to display a list of users with the number of votes (total summary comments.rating per user) they have received.
In result I need:
#foreach ($users as $user)
User id: $user->id has total votes: ...... <br/>
#endif
I want sort my result DESC (from max to min rating votes).
How can I make it?
Try this query:
$users = User::ofRoleType($role)->withCount('commentsReceived')->orderBy('commentsReceived_count', 'desc')->paginate(50);

How to just update a table and add new line with Laravel?

in the database table as below;
public function up()
{
Schema::create('current_adresses', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('current_name',50)->nullable();
$table->string('current_surname',50)->nullable();
$table->string('telephone',25)->nullable();
$table->timestamps();
});
}
I want to do as below;
public function up()
{
Schema::create('current_adresses', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('current_name',50)->nullable();
$table->string('current_surname',50)->nullable();
$table->string('gsm',25)->nullable();
$table->string('telephone',25)->nullable();
$table->timestamps();
});
}
how can I update the new column(gsm column) without refreshing(php artisan migrate:refresh)
Add new migration-
public function up()
{
Schema::table('current_adresses', function($table) {
$table->string('gsm',25)->nullable();
});
}
public function down()
{
Schema::table('current_adresses', function($table) {
$table->dropColumn('gsm');
});
}
See this link for better understanding.

How to attach many to many relationship in Laravel?

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);

Categories