Laravel 5.4 foreign key relation show null in table - mysql

I am trying to save the Client and device foreign keys in my inquiry table but somehow it keeps returning null(my Migration for that is nullable). I get no Errors if I return $Client or $device it Returns a correct id.
This is how the Controller Looks like:
# foreign key in this table rreturns null InquiryController
public function store(Request $request)
{
$input = $request->all();
$client = Client::find($request->input('client_id'));
$device = Device::find($request->input('device_id'));
$stream = new Stream;
$stream->stream_name = $request->input('stream_name');
$stream->save();
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);
$inquiry->save();
}
And this is my Inquiry Model
class Inquiry extends Model
{
protected $table = 'inquiries';
protected $fillable = ['user_id', 'client_id', 'device_id', 'stream_id'];
# relations
public function user()
{
return $this->belongsTo(User::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
public function device()
{
return $this->belongsTo(Device::class);
}
public function stream()
{
return $this->belongsTo(Stream::class);
}
}
this is the relation function for the Client and device model:
public function inquiry()
{
return $this->hasMany(Inquiry::class);
}
The Migration:
public function up()
{
Schema::create('inquiries', function(Blueprint $table)
{
$table->increments('id');
$table->unsignedInteger('client_id')->nullable();
$table->unsignedInteger('device_id')->nullable();
$table->timestamps();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('inquiries');
}

Make sure you have your foreign keys defined in the migration for the inquiry table.
For example:
$table->integer('client_id')->unsigned();
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
Update:
Try saving the model before adding the relationships. Swap it around to:
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->save();
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);

Related

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dream.category_course' doesn't exist

I am getting this error in saving a many-to many relation in laravel eloquent.
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dream.category_course' doesn't exist (SQL: insert into category_course (category_id, course_id, created_at, updated_at) values (5, 6, 2020-07-05 07:48:06, 2020-07-05 07:48:06))
but the table 'category_course' exists in the database dream..
Here is my category model...
class Category extends Model
{
protected $table = 'categories';
protected $guarded = [];
public function Course()
{
return $this->belongsToMany(Course::class)->using(Category_Course::class)->withTimestamps();
}
and this my course model
class Course extends Model
{
protected $table = 'courses';
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsToMany(Category::class)->using(Category_Course::class)->withTimestamps();
}
public function course_content()
{
return $this->hasMany(Course_Content::class);
}
and the customize pivot table
class CreateCategoryCourseTable extends Migration
{
public function up()
{
Schema::create('category__course', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('course_id');
$table->timestamps();
});
}
and here is the controller
public function store(Request $request)
{
$data = $request->validate([
'category_id' => 'required',
'title' => 'required|max:20|min:10',
'description' => 'required|min:30|max:100',
'fee' => 'required|integer|min:1500',
'duration' => 'required|integer|between:1,12'
]);
$category_id = $data['category_id'];
unset($data['category_id']);
$user_id = auth()->user()->id;
$course = \App\user::find($user_id)->course()->create($data);
$course->category()->attach($category_id);
return back();
}
I tried everything.I got but still getting this error....
Anyone have any idea..... please
Two underscores in table name
Schema::create('category__course', function (Blueprint $table)

SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value in Laravel 6

Here, I'm trying to to insert the data in the database but for some reason I am not able to insert the data in the database. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into stages (code, name, description, updated_at, created_at) values (32, dfs, vc, 2020-04-14 06:02:57, 2020-04-14 06:02:57))"
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$location= Stage::create([
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code;
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=>$stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
My migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stages', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('original_id',36)->default('0')->index();
$table->string('code',10)->index()->nullable();
$table->string('name',100);
$table->string('description',200)->nullable();
$table->char('created_by',36)->index();
$table->char('edited_by',36)->index()->nullable();
$table->timestamps();
$table->foreign('created_by')->references('id')->on('users');
$table->foreign('edited_by')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stages');
}
}
In my case i didn't add that field into fillable in my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
}
For laravel 5.6+ you can use Str::uuid() to generate the uuid string;
use Illuminate\Support\Str;
...
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$location= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['stage'=>$stage],200);
}
For below laravel 5.6, you can use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Uuid;
...
public function store(Request $request)
{
$uuid = Uuid::uuid1()->toString();
...
return response()->json(['stage'=>$stage],200);
}
Or you can write an boot method for generating uuid to creating, Eloquent will automatically set id=uuid for every create method. If there are many models with primary key uuid, you can write a trait and use this trait in each models.
use Illuminate\Support\Str;
...
class Stage extends Model
{
/**
* Boot function from laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
});
}
}

Cannot add or update a child row: a foreign key constraint fails (Laravel)

I have errors, and I don't know how to work correctly with Eloquent relationships :c
The category number is taken correctly, but user id is wrong. I think that it is taken from the table models.id but need models.user_id
Here are my tables:
photoset_categories (catalog with photoset types, ex: id = 1, name = 'Studio'; id = 2, name = 'Portrait')
Schema::create('photoset_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->comment('Category name');
});
models (Model data: eye color, height, weight, etc.)
Schema::create('models', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->comment('Model id from users');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); // Foreign key
$table->timestamps();
});
model_photosets (In which photo shoots the model is photographed)
Schema::create('model_photosets', function (Blueprint $table) {
$table->increments('id');
$table->integer('model_id')->unsigned()->index();
$table->foreign('model_id')->references('user_id')->on('models')->onDelete('cascade'); // Foreign key
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('photoset_categories')->onDelete('cascade'); // Foreign key
});
Here are DB Models:
class PhotosetCategory extends Model
{
protected $table = 'photoset_categories';
protected $guarded = ['name'];
public function modelPhotoset()
{
return $this->belongsToMany('App\Models');
}
}
...
class Models extends Model
{
protected $table = 'models';
protected $fillable = ['user_id', 'd_birth', 'birth', 'm_birth', 'y_birth', 'hair_color', 'eyes_color', 'growth', 'weight'];
protected $dates = ['created_at', 'updated_at'];
public function user() {
return $this->belongsToMany('App\User');
}
public function photosets()
{
return $this->belongsToMany('App\PhotosetCategory', 'model_photosets', 'model_id', 'category_id');
}
}
...
class ModelPhotoset extends Model
{
protected $table = 'model_photosets';
protected $fillable = ['user_id', 'category_id'];
}
Controller ModelsController
class ModelsController extends Controller
{
public function editData(Request $request)
{
$title = 'Model data';
$data = Models::where('user_id', Auth::id())->first();
$all_types = PhotosetCategory::all(); // List of photo shoot catagories
if ($request->has('save')) {
$this->validate($request, [
// ...
]);
// UPDATE USER PRO SHOOTS DATA
$data->photosets()->sync($request->get('ps_types'));
}
return view('model.edit', [
'title' => $title,
'data' => $data,
]);
}
}
ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(delavour.model_photosets, CONSTRAINT
model_photosets_model_id_foreign FOREIGN KEY (model_id) REFERENCES
models (user_id) ON DELETE CASCADE) (SQL: insert into
model_photosets (category_id, model_id) values (2, 2))
Error shows that you are trying to insert into model_photosets with model_id 2, but record in models with id 2 doest not exits.

Add two queries at store method in controller

I have this migration table for OFFERS:
public function up()
{
Schema::create('offers', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('article_id')->unsigned();
$table->integer('price');
$table->string('comment');
$table->timestamps();
$table->string('key');
$table->string('title');
$table->timestamp('start');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('article_id')
->references('id')
->on('articles')
->onDelete('cascade');
});
}
Also this at model I have:
class Offer extends Model
{
//
protected $fillable = [
'price',
'comment',
'article_id',
'key',
'start'
];
protected $dates = [
'start'
];
public function setStartAttribute($date){
$this->attributes['start']= Carbon::createFromFormat('m/d/Y h:i a', $date);
}
public function getStartAttribute($date){
return (new Carbon($date))->toRfc2822String();
}
public function user(){
return $this->belongsTo('App\User');
}
public function article(){
return $this->belongsTo('App\Article');
}
}
Now at controller I have just store function:
public function store(Requests\OfferRequest $request)
{
$offer = new Offer($request->all());
Auth::user()->offer()->save($offer);
Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");
return Redirect::back();
}
Now I also have the same model MAXOFFER. The same is migartion and model.
What I want to do is to add at OffersController store method a query that will chech does start excist in maxoffers table and if not then to add new row with data from request, but if excist row with same start value then to check price and if price is higher than current to update that row...
Please help me to rite that query inside store function at offercontroller...
The following query is created by guessing you have a relation maxoffer in Maxoffer model.
$maxoffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))->first();
if($maxoffer==null)
{
Ath::user()->maxoffer()->create($request->all());
}
else
{
if($maxoffer->price < $request->input('price'))
{
$newOffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))
->update(['price'=>$request->input('price')]);
}
}

Laravel 5 - Eloquent relationship returning an empty collection

I'm having trouble with a Laravel 5 relationship. I have 2 models Crew and Event with the corresponding tables crews and events. Crews have many events, and events have one crew. I set up my models and migration as follows:
Schema:
//Crews
Schema::connection('scheduling')->create('crews', function ($table) {
$table->increments('id');
$table->text('name');
$table->boolean('solo');
$table->boolean('active');
$table->text('phone');
});
//Events
Schema::connection('scheduling')->create('events', function ($table) {
$table->increments('id');
// ...
$table->integer('crew_id')->unsigned();
$table->foreign('crew_id')->references('id')->on('crews');
$table->text('notes');
// ...
$table->timestamps();
});
Models:
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Crew extends Model {
public $connection = "scheduling";
public $table = "crews";
public function events() {
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
}
public static function active() {
return Crew::where('active', 1)->get();
}
}
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Event extends Model {
public $connection = "scheduling";
public $table = "events";
public function crew() {
return $this->belongsTo('App\Models\Scheduling\Crew', 'crew_id', 'id');
}
}
If I run Crew::find(102)->events; I end up with an empty collection.
If I run Events::where('crew_id', 102)->get(); I end up with the list of events I expected.
Any idea what I'm doing wrong here?
Your definition of events relation is invalid - you pass the arguments in wrong order.
Replace:
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
with
return $this->hasMany('App\Models\Scheduling\Event', 'crew_id', 'id');
or simply
return $this->hasMany('App\Models\Scheduling\Event');
as you are using the default values for the column names, so no need to pass them to the relation definition.