I am using laravel framework and firebase-database,i am using laravel-firebase-sync package which is responsible for syncing the data to firebase and it's allows to use Eloquent queries upto this part is working fine,i created two migrations and models (User.php and Books.php).
when i hit user registration api the data is being stored in the firebase database ,when i create book(one to many relationships to the users table) the data is being stored in my local-DB(mysql) and it's not reflecting into the firebase,can you suggest how to sync the relations data into firebase
createBooksTable
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
Books.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mpociot\Firebase\SyncsWithFirebase;
class Books extends Model
{
//
use SyncsWithFirebase;
public function users(){
return $this->hasMany(User::class);
}
}
controller
public function createBook(Request $request){
Books::insert(['name' => $request->name,
'user_id' => $request->user_id
]);
return response()->json(['done']);
}
Related
I made an exam-question relationship, every exam has less than 200 questions, but when I run migrations, I go to the PHPMyAdmin and I don't find the foreign key set, it's only a bigint(20) unsigned column and not linked to the exams table.
exam model
<?php
namespace App\Models;
use App\Models\Question;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Exam extends Model
{
use HasFactory;
protected $fillable = [
//
];
public function questions(){
return $this->hasMany(Question::class);
}
}
question model
<?php
namespace App\Models;
use App\Models\Exam;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Question extends Model
{
use HasFactory;
function exam(){
return $this->belongsTo(Exam::class);
}
}
exam migration
<?php
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateExamsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('exams', function (Blueprint $table) {
$table->id();
$table->string('examHash')->unique();
//..
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('exams');
}
}
questions migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('exam_id')->constrained();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('questions');
}
}
I've tried to:
Use this
$table->foreign('exam_id')->references('id')->on('exams');
but
Key column 'exam_id' doesn't exist in table
EDIT:
it can be caused because my engine is not InnoDB, regularly I change the engine to InnoDB to create foreign keys
The method foreignId will only create an UNSIGNED BIGINT and not a foreign key constraint. To also create a constraint you need to call constrained() afterward.
Try this:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('exam_id')->constrained();
$table->timestamps();
});
You can also find more information in the documentation.
Try to add the constrained method when you define the foreign key in question's migration, change:
$table->foreignId('exam_id');
to:
$table->foreignId('exam_id')->constrained();
the problem as I've mentioned in the question is in the engine. so I wrote
$table->engine = 'InnoDB';
in both of question and exam tables...
In laravel i can getFirstNameAttribute in my products model and change the value but I'm create this column "priceArray" and i can not get attributes because The first letter in the second word is capital letters and model can not found this column.
public function getPriceArrayAttribute($value)
{
return 'test';
}
Its not work and can not get "priceArray" column
This is my migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('priceArray')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
This is my product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Products
* #package App\Models
* #property Variants Variants
*/
class Products extends Model
{
use HasFactory;
protected $guarded=[];
protected $changePrice=0;
public function Insert($data)
{
return self::create($data);
}
public function getPriceArrayAttribute($value)
{
return 'test';
}
public function getPriceAttribute($value)
{
return ceil($value);
}
}
The getPriceAttribute is worked but getPriceArrayAttribute does not worked
I think you are trying to modify the priceArray value after it is retrieved from the database, the way you did with ceil() on the price attribute. The only way this works is if you change the column name to price_array. This is by far the simplest fix.
Migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('price_array')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
Model
public function getPriceArrayAttribute($value)
{
return 'test';
}
You must follow Eloquent's rules: you use snake case for the attributes. The getPriceArrayAttribute accessor will automatically be called by Eloquent when you retrieve the value of the price_array attribute.
$table->string('price_array')->nullable();
I currently want to make an API that will get all the lessons by its module_id. These are currently my codes:
Module Migration Table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->string('module_name');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->bigInteger('updated_by')->unsigned()->nullable();
$table->timestamps();
});
Schema::table('modules', function(Blueprint $table) {
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('modules');
}
}
Lesson Migration Table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->bigInteger('module_id')->unsigned();
$table->longText('content');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->bigInteger('updated_by')->unsigned()->nullable();
$table->string('enabled')->nullable();
$table->string('position')->nullable();
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('lesson');
}
}
And this is the GetLessonByModule controller of that API I want to make (getting all the lessons by its module_id):
<?php
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;
class GetLessonByModuleController extends Controller {
public function index() {
$lessons = Lesson::all();
return response($lessons,200);
}
}
The module_id and the ID in the modules table are currently connected as seen in the migration tables. I just don't know how to compose it in my Controller. I also don't know if I should make a new model. Any kind of help/suggestion is deeply appreciated. Thanks in advance.
You can do
<?php
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;
class GetLessonByModuleController extends Controller {
public function index(int $module_id) {
$lessons = Lesson::where('module_id', '=', $module_id)->get();
return response($lessons,200);
}
}
In your api.php there should be definition of the route:
Route::get('lessons-by-module/{module_id}', [\App\Http\Controllers::class, 'index']);
If it works for you and want to do it better, you can go fancy with Laravel routing explicit binding: https://laravel.com/docs/8.x/routing#explicit-binding
I have a users table with the following columns with User model has one to many relationship with phone model.
create_users_table.php
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->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Then I have a phones table, which has a foreign key of user_id
create_phones_table.php
public function up()
{
Schema::create('phones', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->string('phone');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
My User Model
<?php
namespace App;
use App\Phone;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* 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',
];
/**
* Define Relationship
*/
public function phones()
{
return $this->hasMany(Phone::class);
}
}
My Phone Model
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
protected $table = 'phones';
protected $fillable = ['phone' , 'user_id'];
public function user()
{
return $this->belongsTo(User::class);
}
}
I would like to have a third table in my database call phone_user_table.php. Something like a pivot table where I have joined the user table and phone table where I can see all the records. This is my code where I attempt to join the table.
create_phone_user.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePhoneUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('phone_user', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->unsigned();
$table->unsignedBigInteger('phone_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');
$table->timestamps();
$table
->join('users', 'users.id', '=', 'phone_user.user_id')
->join('phones', 'phones.id', '=', 'phone_user.phone_id')
->select('phone_user.*', 'users.name', 'phones.phone')
->get();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('phone_user');
}
}
However, it seems to be giving Base Table phones already exist.
Appreciate all the help given.
Thank you.
This is how it works base on Laravel Many to Many Relationship Docs.
First
You need to create 2 model that you would like to have relationship.
In your example you have USER and PHONE relationship.
In your User Model you need to declare the relationship like this:
public function phones() {
return $this->belongsToMany(Phone::Class);
}
And In your Phone Model you can do like this:
public function users() {
return $this->belongsToMany(User::Class);
}
SECOND
You need to have 3 migration one is for the user, phone and also the phone_user. So it should be look like this.
Phone User Migration
Schema::create('phone_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('phone_id')->index();
$table->unsignedBigInteger('user_id')->index();
$table->timestamps();
$table->foreign('phone_id')->references('id')->on('phones')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Note: You don't need to have the unsignedBigInteger in both user and phone migration.
When you have a user list and a phone list you can now assign the phone to the user like this:
Controller
$user = User::find(1);
$phone = Phone::find(1);
$user->phones()->attach($phone);
I have created a model with migration file by artisan co
mmand
php artisan make:model Staff -m
Created two table in migration file
Schema::create('staffcat', function (Blueprint $table) {
});
Schema::create('staff', function (Blueprint $table) {
});
Now trying to store data to staffcat table from StaffController by
store method. But it's not finding staffcat table :(
I created another model Staffcat. But no luck :(
Create_staff_table File
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStaffTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('staffcat', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('catname');
});
Schema::create('staff', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('user_id');
$table->string('name');
$table->string('designaton');
$table->string('nid')->nullable();
$table->date('dob');
$table->date('doj');
$table->string('blood')->nullable();
$table->string('mpoin')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('staffcat');
Schema::dropIfExists('staff');
}
}
Staff Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Staff extends Model
{
//
}
store method in StaffController
public function store(Request $request)
{
//
$this->validate($request,[
'st_cat_name' => 'required'
]);
$staffinfo = new Staff;
$staffinfo->catname = $request->input('st_cat_name');
$staffinfo->save();
return redirect('/staff')->with('success', 'Staff category Created');
}
Here is the error message
"SQLSTATE[42S02]: Base table or view not found: 1146 Table 'gchsc.staffcats' doesn't exist (SQL: insert into staffcats
(catname, updated_at, created_at)
I want to store data in staffcat table