Hi im working on admin dashboard
and i want to show all users and check if the user blocked get information about the ban from bans table
im using cybercog/laravel-ban to ban users
Laravel 5.8
So i have two table
Users table and Bans table
Bans table has the user id of the banded user in column called : bannable_id
User model :
namespace App;
use Illuminate\Notifications\Notifiable;
use Cog\Contracts\Ban\Bannable as BannableContract;
use Cog\Laravel\Ban\Traits\Bannable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Verified;
class User extends Authenticatable implements MustVerifyEmail,BannableContract
{
use Notifiable;
use Bannable;
protected $fillable = [
'name', 'email', 'password',
'last_login_at',
'last_login_userganet',
'avatar','uid'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function UserBan()
{
return $this->hasOne('App\Ban','bannable_id');
}
Ban Model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ban extends Model
{
protected $fillable = [
'id','expired_at','bannable_type'
];
protected $casts = [
'bannable_type'
];
public function Users()
{
return $this->belongsTo('App\User');
}
}
User Controller :
namespace App\Http\Controllers;
use App\User;
use App\Ban;
use App\Http\Requests\UserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Cog\Contracts\Ban\Bannable;
class UserController extends Controller
{
/**
* Display a listing of the users
*
* #param \App\User $model
* #return \Illuminate\View\View
*/
public function index(User $model,Ban $banModel)
{
return view('users.index', ['users' => $model->paginate(15),'bans'=>$banModel->paginate(15)]);
}
Users schema :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('last_login_provider')->nullable();
$table->string('last_login_useragent')->nullable();
$table->string('last_login_ip')->nullable();
$table->string('uid')->nullable();
$table->string('password');
$table->string('avatar')->nullable();
$table->string('facebook_id')->unique()->nullable();
$table->string('google_id')->unique()->nullable();
$table->string('twitter_id')->unique()->nullable();
$table->string('instagram_id')->unique()->nullable();
$table->enum('user_type',['member','admin'])->default('member');
$table->boolean('blocked')->default(false);
$table->timestamp('banned_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I could not found the bans schema but this is the table of bans :
you are using wrong relationship, you should use polymorphic. Look link below.
https://laravel.com/docs/5.8/eloquent-relationships#one-to-one-polymorphic-relations
it would be something like
User model
public function ban()
{
return $this->morphOne('App\Ban', 'bannable');
}
Ban Model
public function bannable()
{
return $this->morphTo();
}
get all users in controller
define
use App\User;
then
$users = User::all();
then you can foreach it and call ban() method on each
foreach($users as $user)
{
//return associated ban model
$user->ban;
}
Or for better performance, use
User::with(ban)->get();
which highly decrease number of SQL calls. It retrieves all user with ban model. Look at eager loading in link below.
https://laravel.com/docs/5.8/eloquent-relationships#eager-loading
Hope it helps. :)
Related
Employee Controller
<?php
namespace App\Http\Controllers;
use App\Talent\Employee\Requests\EmployeeCreateRequest;
use App\Talent\Employee\EmployeeManager;
use Illuminate\Http\Response;
use App\Talent\User\UserManager;
use App\Talent\Documents\DocumentManager;
use Illuminate\Support\Facades\Hash;
class EmployeeController extends Controller
{
public function __construct(private EmployeeManager $employeeManager,private UserManager $userManager,private DocumentManager $documentManager)
{
}
public function store(EmployeeCreateRequest $request){
$validated = $request->validated();
$userArray=[
'name'=>$validated['first_name']." ".$validated['last_name'],
'email'=>$validated['email'],
'password'=>Hash::make("Introcept#123"),
'role'=>'user'
];
$userCreate=$this->userManager->store($userArray);
return $this->employeeStore($validated,$userCreate,$request);
}
public function employeeStore($validated,$userCreate,$request){
if($request->hasFile($validated['avatar']))
{
$validated['avatar']=$validated['avatar']->store('employeeimages','public');
}
else
{
$validated['avatar']='null';
}
$userId=$userCreate->id;
$userIdArray=[
'user_id'=>$userId,
'status'=>'Active',
];
$employeeArray=array_merge($validated,$userIdArray);
$employeeCreate=$this->employeeManager->store($employeeArray);
$employeeId=$employeeCreate->id;
foreach($validated['documents'] as $document){
$name=$document->getClientOriginalName();
$type=$document->getClientMimeType();
$path=$document->store('employeedocuments','public');
$documentArray=[
'employee_id'=>$employeeId,
'original_name'=>$name,
'type'=>$type,
'path'=>$path,
];
$documentCreate=$this->documentManager->store($documentArray);
}
return response([
'userId'=>$userId,
'employeeId'=>$employeeId,
'message'=>'Personal detail added successfully',
],Response::HTTP_OK);
}
}
Employee.php
<?php
namespace App\Talent\Employee\Model;
use App\Talent\Documents\Model\Document;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'contact_number',
'date_of_birth',
'current_address',
'pan_number',
'bank_account_number',
'avatar',
'status',
'user_id',
];
**EmployeeRequest.php**
<?php
namespace App\Talent\Employee\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EmployeeCreateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|email|unique:employees,email',
'contact_number'=>'required|string',
'date_of_birth'=>'required|date',
'current_address'=>'required|string',
'pan_number'=>'string|nullable',
'bank_account_number'=>'string|nullable',
'avatar' => 'nullable|image|mimes:jpg,jpeg,png',
'documents'=>'required',
'documents.*'=>'max:5000|mimes:pdf,png,jpg,jpeg',
];
}
public function messages()
{
return [
'documents.max' => "Error uploading file:File too big.Max file size:5MB",
];
}
}
EmployeeMigration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->restrictOnDelete();
$table->string('status');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('contact_number');
$table->date('date_of_birth');
$table->string('current_address');
$table->string('pan_number')->nullable();
$table->string('bank_account_number')->nullable();
$table->string('avatar')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
};
I am trying to create an API that stores employee personal details into the database. Here, image field is optional so I made avatar field nullable in both migration and validation request as well. But when I try save details into the database without uploading image it shows undefined avatar. I don't know what happening here any help or suggestions will be really appreciated. Thank you.
You are using the string value of null instead of the keyword null.
This question already has answers here:
How to fix error on Foreign key constraint incorrectly formed in migrating a table in Laravel
(29 answers)
Closed 7 months ago.
I have a Plan model and a User model, the User has one plan, and the plan belongs to many Users;
When I run php artisan migrate:fresh I get this error:
**
SQLSTATE[HY000]: General error: 1005 Can't create table service6_servicelandv1.0.users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table users add constraint users_plan_id_foreign foreign key (plan_id) references plans (id) on delete set null)
**
here are the migrations:
User migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string("avatar_name")->default("default-male.jpg");
$table->string('username')->unique();
$table->string("email")->unique();
$table->string('password');
$table->string("role")->default('Regular')->nullable();
$table->string("address")->nullable();
$table->bigInteger("reputation")->default(0);
$table->string("phone_number")->nullable();
$table->float("wallet", 10, 2)->default(0);
$table->unsignedBigInteger("plan_id")->nullable();
$table->unsignedBigInteger("option_id")->nullable();
$table->unsignedBigInteger("category_id")->nullable();//fav_category
$table->rememberToken();
$table->timestamp('email_verified_at')->nullable();
$table->timestamp("created_at")->useCurrent();
$table->timestamp("updated_at")->useCurrent();
$table->foreign("plan_id")->references("id")->on("plans")->onDelete('set null');
$table->foreign("option_id")->references("id")->on("options")->onDelete('set null');
$table->foreign("category_id")->references("id")->on("categories")->onDelete('set null');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
And for the Plan migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('plans', function (Blueprint $table) {
$table->id("id");
$table->string("name");
$table->integer("ads_number");
$table->decimal('amount_credit', 9, 3, true);
$table->decimal('price', 9, 3, true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('plans');
}
};
User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens; // comment this
use Laravel\Passport\HasApiTokens; // include this
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
"avatar_name",
'username',
'email',
'password',
"address",
"role",
"reputation",
"wallet",
"phone_number",
"plan_id",
"option_id",
"category_id",
'confirmation_password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the image url.
*
* #param string $value
* #return string
*/
public function getAvatarNameAttribute($value){
return asset('storage/avatars/' . $value);
}
public function role(){
return $this->hasOne(Role::class);
}
public function category(){
return $this->hasOne(Category::class);
}
public function plan(){
return $this->hasOne(Plan::class);
}
public function option(){
return $this->hasOne(Option::class);
}
public function postStars(){
return $this->hasManyThrough(PostStar::class, Post::class);
}
}
Plan Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Plan extends Model
{
use HasFactory;
protected $fillable=[
"name",
"ads_number",
"amount_credit",
"price"
];
public function user(){
return $this->belongsTo(User::class);
}
}
Please I am really stuck for like two hours now and I don't understand what's going on??! what's wrong with that set null??
You can simply use this method to assign foreign keys:
$table->foreignId('user_id')
->nullable()
->constrained()
->onUpdate('cascade')
->onDelete('set null');
This is way better than other methods.
Check Documentation
In Laravel you can use nullOnDelete()
$table->foreignId('plan_id')
->nullable()
->constrained('plans')
->nullOnDelete();
Go through the Laravel Foreign Key Constraints to get some idea on Foreign Key declarations
So I'm trying to have plans associated to the current user.
I have modal and migration called Plan. I have a method called user that I use the belongsTo() to get all the users that's associated to that plan. I'm not sure why its not working
Modal
namespace App\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Plan extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'stripe_plan',
'cost',
'description'
];
public function getRouteKeyName()
{
return 'slug';
}
public function user()
{
return $this->belongsTo(User::class);
}
}
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePlansTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('plans', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->string('stripe_plan');
$table->float('cost');
$table->text('description')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('plans');
}
}
I call the Plan model from my controller
controller that calls the model
the view that i call the users method
It show blanks
the output on the screen
You didn't load the relationship. You can use the with() to achieve this.
<?php
// controller
class PlanController extends Controller {
public function method(){
$plans = Plan::with('user')->get();
// Continue with Code
// if you use compact to pass data to the view
// else $plans = Plan::all();
// views('view_name', ['plans' => $plans] should word just fine
}
}
I am trying to make a chatbox using Laravel and Vue.js. I am following this online tutorial. I have followed almost every step to a tee and I cannot tell why I am not getting the desired result. Here is what I have done thus far:
I have created a User model and a Message model with the correct table columns and migrations. In the User model I established a hasMany relationship with the Message model. In the Message model, I established a belongsTo relationship with User.
When I go into tinker, I can do:
factory(App\User::class)->create()
just fine, like the guy in the tutorial can do. However when I try to do:
App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
I get this error:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::messages does not exist.'
Here is my code:
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','api_token',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function messages()
{
return $this->hasMany(Message::class);
}
}
Message Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Message Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('message');
$table->integer('user_id')->unsigned();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
If you could let me know what I am doing wrong, I would really appreciate it. Thanks.
Restart the php artisan tinker and re-run your code. It works:)
Seems you are getting this error:
BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::created does not exist.'
To save models to relationships, use create method, but not created method, for example:
App\User::find(4)->messages()->create(['message'=>'Hello from Sharon']);
instead of App\User::find(4)->messages()->created(['message'=> "Hello from Sharon"])
try to use
App\User::find(4)->messages()->create(['message'=> "Hello from Sharon"])
or
App\User::find(4)->messages()->save(['message'=> "Hello from Sharon"])
Below is my LevelOneModel. I can't seem to figure out what I have not included. Please I need assistance.
What I want to achieve is to have all the users id in the levelone table
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LevelOneModel extends Model
{
public function users(){
return $this->hasMany('App\User');
}
}
Below is my User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'phone',
'bank_name',
'acct_name',
'acct_number',
'profile_pix',
'sme',
'other_sme',
'password',
];
public function levelone()
{
return $this->belongsTo('App\LevelOneModel');
}
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
And below is my level one migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLevelOneTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('level_one', function (Blueprint $table) {
$table->increments('id');
$table->integer('users_id')->unsigned();
$table->integer('upline_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('level_one');
}
}
Thanks
I notice some things in your code....
Looking at your classes, I understand the relationship is like this
a user belongs to one LevelOne only.
a LevelOne can have multiple users
If that is correct, the relationship is incorrectly build in the migration. Because you are adding a user_id to the level_one table.
It should be the other way around: the user tabel must contain a level_one_id.
And you should add it in the User migration, something like:
$table->int('level_one_id');
$table->foreign('level_one_id')->references('id')->on('level_one');
Now you have (in the database) a connection between User and LevelOne.
Now, if you query a user in your code, you should be able to get the LevelOne stuff as well. Make sure to really read the official Laravel documentation on relationships! It will really help you with examples.