Model relationship creation uses the wrong field in Laravel - laravel

I want to create a new model using the relationship between a two model module and chapter and they have HasMany relationship between them as follow :
//Module mode
public function chapters()
{
return $this->hasMany(Chapter::class, 'module_slug', 'slug');
}
//Chapters Model
public function module()
{
return $this->belongsTo(Module::class, 'module_slug', 'slug');
}
And here's how I'm storing the models :
$module = Module::create([
'title' => $request->module_title,
'icon' => $request->module_title
]);
$module->chapters()->create([
'pdf_url' => $path,
'title' => $request->chapter_title
]);
The Issue :
The problem I got is that the $module->chapters()->create() is using the id not the slug which I'm specifying as the primary key like this :
//Module model
protected $primaryKey = 'slug';
protected $keyType = 'string';
//Chapters model
protected $primaryKey = 'slug';
protected $keyType = 'string';
I don't know why it uses the id field like this screenshot :

Add this to your models:
public $incrementing = false;

Related

How to store the actual user logged into my database and display it as a created by field for my CRUD?

I have this code in my controller:
public function store(StoreRequest $request)
{
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
$request->validate([
'creado_por' => 'string'
]);
return ComprasNotificacionCancelacion::create([
'nombre' => request('nombre'),
'correo' => request('correo')
]);
}
This is the model:
protected $table = 'compras_notificacion_cancelacions';
protected $primaryKey = 'id';
protected $guarded = ['id'];
protected $fillable = [
'nombre',
'correo',
'creado_por'
];
protected $dates = [
'fecha_creacion',
'fecha_modificacion'
];
Could you help me, please?
Your question is not clear, but what you are trying to do is add logged in user as the creado_por here is how you can achieve that.
public function store(StoreRequest $request)
{
$request->validate([
'creado_por' => 'string'
]);
//here you can use either Auth()->user()->id or $request->user()->id
return ComprasNotificacionCancelacion::create([
'nombre' => $request->nombre,
'correo' => $request->correo,
'creado_por' => $request->user()->id
]);
}
additionally here are somethings you could improve. You can access same Auth()->user() from $request like $request->user().
You don't need the below codes.
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
and if using id as id no need to mention it
protected $primaryKey = 'id';
The way I store the author of an entry is that I have a created_by column in the database and I make sure that contains the right ID inside the model. Here's a trait I use, that I call CreatedByTrait.php and use it on the models that need it:
<?php namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Model;
trait CreatedByTrait {
/**
* Stores the user id at each create & update.
*/
public function save(array $options = [])
{
if (\Auth::check())
{
if (!isset($this->created_by) || $this->created_by=='') {
$this->created_by = \Auth::user()->id;
}
}
parent::save();
}
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function creator()
{
return $this->belongsTo('App\User', 'created_by');
}
}

Laravel many to many relationship with uuid returns always empty

I use Laravel 5.8 and changed my model's autoincrement id to uuid. Since then I have some trouble with my many-to-many relationship that was defined between 2 of my models Event and User (with pivot table events_users).
The problem :
Now when I request all element that join both table (I have 2 records in my pivot table) I always get an empty array back.
When debugging the sql, I see that the where clause param is not set :
// Generated sql
select `users`.*, `events_users`.`event_id` as `pivot_event_id`, `events_users`.`user_id` as `pivot_user_id`, `events_users`.`created_at` as `pivot_created_at`, `events_users`.`updated_at` as `pivot_updated_at`
from `users`
inner join `events_users` on `users`.`id` = `events_users`.`user_id`
where `events_users`.`event_id` = ?
// Bindings :
Array
(
[0] =>
)
Has someone any clue what I'm missing here ?
Here are the definition of my models :
class Event extends Model
{
protected $primaryKey = 'id';
protected $keyType = 'string';
public $incrementing = false;
// here some other model methods, fillable property, etc.
public function users()
{
return $this
->belongsToMany(User::class, 'events_users', 'event_id', 'user_id')
->withTimestamps();
}
}
Same declaration for User model, but with relation
public function events()
{
return $this
->belongsToMany(Event::class, 'events_users', 'user_id', 'event_id')
->withPivot(['created_at', 'updated_at']);
}
Then I retrieve the relations from the service with :
public function getSubscriptions($eventId)
{
$eventId = 'a1b7c5d6-8f86-44f4-f31a-46e32917d5c0'; // for debug purpose only
$event = Event::find($eventId);
foreach ($event->users as $user) {
print_r($user); die; // It never loops here as its length is 0 but should be 2...
}
\DB::listen(function ($query) {
print_r($query->sql);
print_r($query->bindings);
// $query->time
});
$subscriptions = $event
->users()
->get();
die;
return $subscriptions;
}
My DB contains the records
The problem was about another declaration in my models where I list the property.
I've initialized an id property there, which is probably in conflict with the uuid type or I don't know exactly what cause this drama...
Anyway, removing this line let the app work correctly.
/**
* #var array
* Rules used for fields validation
*/
public $rules = array(
'title' => 'required|string|max:255',
'start_date' => 'required|date|date_format:Y-m-d',
'end_date' => 'required|date|date_format:Y-m-d|after_or_equal:start_date',
'location' => 'string|max:254',
'latitude' => 'numeric',
'longitude' => 'numeric'
);
public $id = ""; // This is the line that create the bug... Remove it and it works !
public $title = "";
public $start_date = "";
public $end_date = "";
public $location = "";
public $latitude = "";
public $longitude = "";

Fetch data from another table to select in laravel 5.5

I got a problem when I try to fetch data from table to select.
here is my Mahasiswa model :
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','email','tempat','tanggal','link','id_jurusan'];
protected $table = 'mahasiswa';
public function jurusan(){
return $this->belongsTo('App\Jurusan');
}
here is my MahasiswaController :
public function create()
{
$data['data']= Mahasiswa::with('jurusan')->get();
return view('Mahasiswa.mahasiswaInsert',$data);
}
and here is my blade view :
{{ Form::select('id_jurusan',['' => 'Pilih Jurusan']+$data ,1,['id' => 'jurusan', 'style' => 'display:inline-block','class' => 'blue-text']) }}
I just wanna get the data from table jurusan and fetch to the select ?? how to do that?? Thanks in advance, and sorry for my bad grammar.
Change your model.
protected $table = 'mahasiswa';
protected $fillable = ['nim','nama','alamat','jenis_kelamin','no_tlp','email','tempat','tanggal','link','id_jurusan'];
public function jurusan(){
return $this->belongsTo('App\Jurusan','id_jurusan','id');
}
And i think this enough your solutions for controller,
public function create()
{
$data= Jurusan::get()->pluck('name','id');
return view('Mahasiswa.mahasiswaInsert',compact('data'));
}

Laravel insert data to one to one relation table

How can I insert data (that linking each other) to the table 'PEMBATALAN' that has one to one relation (have foreign key in both table) to the other table 'PERMINTAAN'.
here is the 'pembatalan' model code:
class Pembatalan extends Model
{
public $table = "PEMBATALAN";
public $primaryKey = "ID_PEMBATALAN";
public $fillable = array(
'PERMINTAAN_ID',
'ALASAN_PEMBATALAN',
'TGL_PEMBATALAN',
'FILE_PEMBATALAN',
'STATUS_PEMBATALAN',
);
public function permintaan() {
return $this->belongsTo('Permintaan', 'PERMINTAAN_ID', 'ID_PERMINTAAN');
}
}
'Permintaan' model code:
class Permintaan extends Model
{
public $table = "PERMINTAAN";
public $fillable = array(
'NOMOR_TICKET',
'TGL_PERMINTAAN',
'NAMA_REQUESTER',
'PEMBATALAN_ID',
);
public $primaryKey = "ID_PERMINTAAN";
public function tikpro() {
return $this->belongsToMany('Tikpro','TIKPRO_ID','ID_TIKPRO');
}
public function pembatalan() {
return $this->hasOne('Pembatalan','PEMBATALAN_ID','ID_PEMBATALAN');
}
}
Thanks in advance
Create your Permintaan and then use that reference to create the relation
Only Pembatalan needs a foreign key of Permintaan or the other way around.
$p = Permintaan::create([
'NOMOR_TICKET' =>$value,
'TGL_PERMINTAAN' =>$value,
'NAMA_REQUESTER' =>$value,
]);
$p->pembatalan()->create([
'ALASAN_PEMBATALAN' =>$value,
'TGL_PEMBATALAN' =>$value,
'FILE_PEMBATALAN' =>$value,
'STATUS_PEMBATALAN' =>$value,
]);
Laravel docs has a very good explanation on one to one relationships using hasOne and belongs to

laravel eloquent doesn't use protected table name

In my model i added protected $table, but when i'm going to use it laravel does't use it. This is my role models:
class Role extends Model
{
protected $table = 'role';
protected $primaryKey = 'ROLE_ID';
protected $casts = [
'ACTIVE' => 'boolean',
];
protected $fillable = [
'ROLE', 'ACTIVE', 'TYPE'
];
public $timestamps = false;
public function groups()
{
return $this->belongsToMany(Group::class, GroupRole::class, 'ROLE_ID', 'GROUP_ID');
}
}
And this is Group model:
class Group extends Model
{
protected $table = 'groups';
protected $primaryKey = 'GROUP_ID';
protected $fillable = [
'GROUP_ID', 'GROUP_NAME', 'PARENT_GROUP', 'ACTIVE'
];
protected $casts = [
'ACTIVE' => 'boolean',
];
public $timestamps = false;
public function type()
{
return $this->belongsTo(GroupType::class, 'TYPE', 'TYPE_ID');
}
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class, 'GROUP_ID', 'ROLE_ID');
}
}
And this is group_role table model. It handles many to many relation between role and group:
class GroupRole extends Model
{
protected $table = 'group_role';
protected $primaryKey = 'GROUP_ROLE_ID';
protected $fillable = [
'COMMENT', 'ROLE_ID', 'GROUP_ID'
];
public $timestamps = false;
}
Problem begin when i want to use this models. For example:
$role = App\Role::first();
$groups = $role->groups;
Laravel returns this error messages:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'favian_mydb.App\GroupRole' doesn't exist (SQL: select groups.*, App\GroupRole.ROLE_ID as pivot_ROLE_ID, App\GroupRole.GROUP_ID as pivot_GROUP_ID from groups inner join App\GroupRole on groups.GROUP_ID = App\GroupRole.GROUP_ID where App\GroupRole.ROLE_ID = 1)
I tried to replace App\GroupRole with group_role and executing in mysql. It works fine. Am i missing something?
The Problem is in your roles relation:
public function roles()
{
return $this->belongsToMany(Role::class, GroupRole::class,'GROUP_ID','ROLE_ID');
}
The belongsToMany expects the intermediate table name as second argument, not the class name.
So you have to define it like this:
public function roles()
{
return $this->belongsToMany(Role::class, 'group_role','GROUP_ID','ROLE_ID');
}
I think the problem is in you relation functions. Try to use strings instead of Model::class.
Example:
return $this->return $this->belongsTo('App\GroupType', 'TYPE', 'TYPE_ID');
Hope this works.

Resources