Count Referer in laravel 6 - php

I build a referral system Using Laravel and VueJS. i want count referral each users.
I implement count it from User Model
public function getCountReferrerAttribute()
{
$user = User::where('referred_by', auth()->user()->name)->count();
return $user;
}
And i try to get it from Vuejs
Its show Referrer Count for Every User...
User Schema
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('referral_code')->unique()->nullable();
$table->string('referred_by')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Thanks in advance...

Assuming you are calling this function for every user on your table, your query is getting all user that is referred by the currently logged in user because of auth()->user()->name, instead your function should use the name of the user itself.
So it will look something like this
public function getCountReferrerAttribute()
{
$user = User::where('referred_by', $this->name)->count();
return $user;
}

Related

give every user role for every page on laravel 5.5

im working on a laravel 5.5 project
and they told me to make role for every page
create edit update delete search softdelete
so i have created user table
this is the migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_name',40)->unique();
$table->string('user_email',40)->nullable()->unique();
$table->string('user_phone',40)->nullable()->unique();
$table->integer('user_department');
$table->string('password',60);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
and i have created model table this is the migration
public function up()
{
Schema::create('models', function (Blueprint $table) {
$table->increments('id');
$table->string('model_name',40)->unique();
$table->timestamps();
$table->softDeletes();
});
}
and i have created modelroles table
public function up()
{
Schema::create('modelroles', function (Blueprint $table) {
$table->increments('id');
$table->integer('model_id');
$table->integer('user_id');
$table->integer('create');
$table->integer('read');
$table->integer('update');
$table->integer('softdelete');
$table->integer('delete');
$table->integer('restore');
$table->integer('search');
$table->timestamps();
});
}
and i have created middlewaer called roleMiddleware
this is the code
use Closure;
class roleMiddleware
{
public function handle($request, Closure $next)
{
return $next($request);
}
}
so how can i connect them together in the middleware
what i want is to give every user role in every page create read update delete ect
mean check the url the request come from
and check the user id
and check the model id
and check the user_id and the model_id inside modelroles
and if he can create edit update delete on the model
i dont want to use packages like this
https://github.com/laravel-enso/RoleManager
or this
https://github.com/Zizaco/entrust
i dont want to connect users with global role
i want to give every user role for every controller

hasMany relationship is null

I'm new to Laravel 5.0.
I'm trying to make a hasmany relationship between my two models, User and Device.
If in tinker I do App\user::first()->device the result is null
I populated the users and devices tables with some dummy data and the single find() work.
I searched on StackOverflow but I could't find out a solution
Here's my users table
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
my devices table
public function up()
{
Schema::create('devices', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->double('lat', 15, 8);
$table->double('lon', 15, 8);
$table->timestamps();
});
}
and my function in the User Model
public function device()
{
return $this->hasMany('App\Device');
}
Thank you all
The code was right, I found out sometimes tinker needs to be rebooted after the changes in the code

Laravel 5.3: Adding model method causing status code 500

I have written a bunch of test cases for the registration form for a Laravel 5.3 project. One of the basic test cases is to insert fake data and check for the proper redirection. My test case code:
/**
* Check for the registration form
*
* #return void
*/
public function testNewUserRegister(){
// Generate a ranom name
$thisName = str_random(8);
// Genearte a random email
$thisEmail = str_random(8)."#google.com";
// Type some valid values
$this->visit('/register')
->type($thisName,'name')
->type($thisEmail,'email')
->type('password123','password')
->type('password123','password_confirmation')
->press('Register')
->seePageIs('/home');
}
Everything was working properly and no complaints from PHPUnit. But when I included the following method in my User model:
// Function to check for the adminship
public function isAdmin(){
// Check if the user is logged in
if(Auth::check()){
// Check if the user is admin
if(Auth::user()->isAdmin){
return true;
}
}
// Return false if not
return false;
}
The above test case testNewUserRegister fails and following is the error message:
There was 1 failure:
1) AuthTest::testNewUserRegister
A request to [http://localhost/home] failed. Received status code [500].
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:220
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:92
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:150
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:92
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:125
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:580
/var/www/html/project-css/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:567
/var/www/html/project-css/tests/AuthTest.php:26
Caused by
ErrorException: Undefined property: App\User::$isAdmin in /var/www/html/project-css/app/User.php:36
Further, following is the database schema:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('isAdmin')->default(false);
$table->boolean('hasAccess')->default(true);
$table->rememberToken();
$table->timestamps();
});
Not a duplicate here is why:
It's not due to the camel case as suggested. When included the following parameter the testing still fails:
public static $snakeAttributes = false;
Also modified the schema into camel case didn't solve my issue still the test fails.
You can go about this 2 different ways.
1. Change the migration
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->boolean('is_admin')->default(false);
$table->boolean('has_access')->default(true);
$table->rememberToken();
$table->timestamps();
});
2. Create an Accessor
In your User model create the following function:
public function getIsAdminAttribute()
{
return $this->isAdmin;
}
This will just return the value of the isAdmin column in the database.
I would personally go with the first option, it's a better naming convention for tables and keeps everything organized.
I would do this:
In your User model:
public function isAdmin(){
// this looks for an admin column in users table
return $this->admin;
}
Now add an admin field to your database:
php artisan add_admin_to_users_table
In your migration:
public function up()
{
Schema::table('users', function ($table) {
$table->boolean('admin')->default(0);
});
}
public function down(){
Schema::table('users', function ($table) {
$table->dropColumn('admin');
});
This should work properly.

Laravel. Update two tables at one POST method

I have this code right there, this code is working fine and data is successfully stored to table "reports". But I also want to update Users table and their field Credits also. How can I do this in this function ? I also have the relationship between these two tables "reports" and "users".
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
$report->save();
return redirect()->back();
}
Users Table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('credits');
$table->enum('role', ['user', 'admin'])->default('user');
$table->rememberToken();
$table->timestamps();
});
Reports table
Schema::create('reports', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('credits');
You just need to add the logic to update the user (assuming you have a relationship method called user):
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
// if the report has a user, update it
if ($report->user) {
$report->user->credits += Input::get('credits');
$report->user->save();
}
$report->save();
return redirect()->back();
}

Automaticlly attach to pivot table in Laravel 5

I currently have a Users to Groups Relationship (ManyToMany) with a pivot table group_user. I want the user to be able to create a group but once creating the group, how do I make it, that the creator becomes member of this group?
Currently I have
My Pivot Table (group_user):
Schema::create('group_user', function(Blueprint $table)
{
$table->integer('group_id')->unsigned()->index();
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
My Groups table (groups):
Schema::create('groups', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
My Users table (users):
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('name');
$table->string('lastname');
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
My models ofcourse have the following: User.php
public function groups()
{
return $this->belongsToMany('App\Group');
}
Group.php
public function users()
{
return $this->belongsToMany('App\User');
}
What create function should I write in my controller so that when a User creates a Group, that he automaticly becomes member of this group (automaticlly make the pivot relationship)?
This should work, make sure you implement validation, ect.
public function store(Request $request)
{
$group = Group::create([ // <-- if names are unique. if not, then create is fine
'name' => $request->get('name')
]);
auth()->user()->groups()->attach([$group->id]);
return view('your.view');
}
Also make sure to add:
use App\Group;
See attach() and detach().
$user = User::find(1);
$user->groups()->attach(10); // pivot relationship of this user to group of id 1.
OR
$group = Group::find(10);
$user->groups()->save($group);
For many groups of this user:
$user->groups()->sync(array(1, 2, 3));

Categories