How to save One to Many Relationship to database - laravel-5

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.

Related

Why "set null" is not working in onDelete in Laravel 9? [duplicate]

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

How to fix Base table or view not found database table using laravel

I have common error and I don't know what I called on this problem. so please I will let explain to you the problem that I encounter.
So right now i'am using laravel 5.7 and I did multiple auth guard. so right now I have login for salesperson so I created migration table for all sales person users. so I already migrated 2020_05_16_190202_create_salesperson_table.php successfully created to the database.
Lets move to the error that I encounter after I login, note that I have sales_person table.
after I click the submit button I have error and the error is Base table or view not found: 1146 Table 'dbname.sales_people' doesn't exist (SQL: select * from sales_people where email = example#gmail.com limit 1)
so why is it my App/Salesperson looking for sales_people? I have no sales_people table on my database. I only have sales_person. So I really don't understand why this error gives me.
Problem: Why is it my App/Salesperson looking for sales_people table which is not created to the migration?
Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class SalesPerson extends Authenticatable
{
use Notifiable;
protected $guard = 'salesperson';
protected $fillable = [
'first_name',
'middle_name',
'last_name',
'email',
'password',
'mothers_maiden_name',
'emergency_contact',
'emergency_contact_num',
'address',
'tin_num',
'valid_photo',
'parent_id',
'created_at'
];
protected $hidden = [
'password', 'remember_token',
];
}
Migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSalespersonTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('salesperson', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('middle_name');
$table->string('last_name');
$table->string('email');
$table->string('password');
$table->string('mothers_maiden_name');
$table->string('emergency_contact');
$table->string('emergency_contact_num');
$table->string('address');
$table->string('tin_num');
$table->string('valid_photo');
$table->enum('member_status', array('Active','Pending'))->default('Pending');
$table->string('parent_id');
$table->string('sponsor_id');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('salesperson');
}
}
DB Table:
Eloquent Model Conventions
Table Names
Note that we did not tell Eloquent which table to use for our SalesPerson model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the SalesPerson model stores records in the sales_persons table. You may specify a custom table by defining a table property on your model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class SalesPerson extends Authenticatable
{
use Notifiable;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'salesperson';
// ... everything else you already have
}
You could also change the name of the table to follow the conventions, that way you won't have to make it explicit in the model:
Schema::create('sales_persons', function (Blueprint $table) {
// ...
});
As you can see here: https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L1377
Laravel creates a tablename using:
return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
Because you have not provided a name, it is created.
You should force the name in your modal using:
class SalesPerson extends Authenticatable
{
use Notifiable;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'salesperson';
// the rest
}

Laravel Showing all users and check if belong to Bans table

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. :)

BadMethodCallException with message 'Method Illuminate\Database\Query\Builder::messages does not exist.'

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"])

Relationship function is not working in laravel

relationship function is not working of any type. i am creating 2 tables relationship of one to many but it is not working i have no idea at all about that i have follow tutorials and laravel documentation as well but all is vain please guide me thanks.
//this is 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','image','candidate_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//
}
// and this is candidate model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Candidate extends Model
{
public function user()
{
return $this->hasOne('app\User');
}
}
It shows your model User store candidate_id, so there is 1 Candidate many User..
in Candidate model (Table Name should be candidates)
public function user()
{
return $this->hasMany(User::class);
}
in User model (Table Name should be users)
public function candidate()
{
return $this->belongsTo(Candidate::class);
}
All things were correct, I just call a single attribute of a second table instead of function. In Laravel we call function of related table not its attribute this is the mistake.

Resources