Laravel 6 - Unique custom id doesn't increment after table get empty - php

Current Situation
I have custom unique increment makes the code looks like this
but when i make that table empty and add new value it looks like this
Expected Situation
after I made the table empty and make new input the custom_id should follow the id
The Model
class Transaction_in extends Model
{
protected $table = 'transaction_ins';
protected $primaryKey = 'idTransactionsIN';
public $timestamps = true;
public $incrementing = false;
protected $guarded = [];
public static function getidTransactionsIN(){
DB::table('transaction_ins')->orderBy('id','desc')->take(1)->get();
}
}
The Controller
public function store(Request $request)
{
$request->validate([
'transaction_in_date' => 'required',
]);
Transaction_in::getidTransactionsIN();
$newtransaction_inId = Transaction_in::max('id') + 1;
$Getnewtransaction_inId = sprintf('TIN%04d', $newtransaction_inId);
$transaction_in = new Transaction_in();
$transaction_in->idTransactionIN = $Getnewtransaction_inId;
$transaction_in->date = $request->input('transaction_in_date');
$transaction_in->save();
}

You can set custom_id after creating model and it's a bit safer in case of many operations:
public function store(Request $request)
{
$request->validate([
'transaction_in_date' => 'required',
]);
$transaction_in = Transaction_in::create(['date' => $request->input('transaction_in_date')]);
$transaction_in->update(['custom_id' => sprintf('TIN%04d', $transaction_in->id)]);
}
you should also just in case wrap it in database transaction.

Related

Create one to many table relationship with text input Laravel

I have two tables with a one to many relationship - gratitude_journal_entries and self_gratitudes. Multiple self gratitudes (which are submitted as text entries by the user) can apply to 1 gratitude_journal_entry. The data is passed to these two tables via a form.
I am trying to store the self gratitude text entries in an array and then pass these to the self_gratitude table along with the foreign key from the gratitude_journal_entries table.
The problem I'm having is I'm not sure how to take the input from the array and store this in the self_gratitude column.
Here are the columns for the gratitude_journal_entries table
Here are the columns for the self_gratitudes table
Here are the models and the store method in my controller
class SelfGratitudes extends Model
{
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
class GratitudeJournalEntry extends Model
{
protected $table = 'gratitude_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function selfGratitudes()
{
return $this->hasMany(SelfGratitudes::class);
}
public function store(Request $request)
{
$this->validate($request, [
]);
$gj_entry = new GratitudeJournalEntry;
$gj_entry->user_id = auth()->user()->id;
$gj_entry['entry_date'] = date('Y-m-d H:i');
$self_gratitudes = $request->has('self_gratitudes') ? $request->get('self_gratitudes') : [];
$tj_entry->save();
$gj_entry->selfGratitudes()->sync($self_gratitudes);
return redirect('/dashboard')->with('success', 'You submitted a new journal entry');
}
If you want to keep array in database you can use casting on your columns:
laravel document
class SelfGratitudes extends Model
{
protected $casts = [
'self_graitude' => 'array',
];
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}

Why is laravel push giving me a error 1364: Field 'question_entity_id' doesn't have a default value?

I'm very new to Laravel (this is my first time using it) and I'm trying to store some data that I made in a post request to my api. I keep on getting a General error: 1364 Field 'question_entity_id' doesn't have a default value.
I'm trying to use Laravel's push method to save the itemBank model and all it's relationships I define below but I get the error above. I've tried manually setting foreign_key relationships like `$itemBank->question_entity_id = $questionEntity->id' but this gives me the same error. I'm specifically trying to figure out why question_entity_id isn't getting filled (I know that the error could be resolved by making the field nullable or giving question_entity_id a default value).
Here are the relevant models:
class ItemBank extends Model
{
// table name
protected $table = "item_bank";
// do no use default timestamp fields
public $timestamps = false;
// item_bank relationships to other Models/tables
public function questionEntity() {
return $this->hasOne('App\QuestionEntity', 'id', 'question_entity_id');
}
public function optionEntity() {
return $this->hasMany('App\OptionEntity', 'item_id', 'id');
}
public function tagItemRel() {
return $this->hasOne('App\TagItemRel', 'item_id', 'id');
}
}
class QuestionEntity extends Model
{
// table name
protected $table = 'question_entity';
// disable default timestamps
public $timestamps = false;
public function itemBank() {
return $this->belongsTo('App\ItemBank', 'id', 'question_entity_id');
}
}
Here is the code where I'm trying to store my data:
public function store(Request $request)
{
$data = $request->all();
$itemBank = new ItemBank();
//save question body text
$questionEntity = new QuestionEntity();
$questionEntity->question = $data['questionBody'];
$itemBank->questionEntity()->save($questionEntity);
// save correct answer
$itemBank->correct_answers = $data['correctAnswer'];
//save question options
$choices = ['A', 'B', 'C', 'D'];
//$optionEntities = [];
foreach($choices as $choice) {
$optionEntity = new OptionEntity();
$optionEntity->choice = $data['choice' . $choice];
$optionEntity->choice_label = $choice;
$optionEntity->itemBank()->associate($itemBank);
}
//$itemBank->optionEntity()->saveMany($optionEntities);
//create new ItemTag Model
$itemTag = new ItemTag();
$itemTag->tag_name = $data['topic'];
//create new TagItemRel Model
$tagItemRel = new TagItemRel();
$tagItemRel->itemTag()->save($itemTag);
$tagItemRel->itemBank()->associate($itemBank);
$itemBank->push();
return $itemBank;
}
Here are the relevant migration files:
QuestionEntity:
Schema::create('question_entity', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('question', 500);
});
ItemBank:
Schema::create('item_bank', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('question_entity_id');
$table->string('correct_answers', 1);
$table->foreign('question_entity_id')->references('id')->on('question_entity');
});
Add question_entity_id in your ItemBank model, like this.
protected $fillable = [
'question_entity_id',
];
So your ItemBank model will look like this.
class ItemBank extends Model
{
// table name
protected $table = "item_bank";
protected $fillable = [
'question_entity_id','correct_answers'
];

How to correctly store the date on the database from the model Laravel

please help me i'm using Laravel 5.4 and i want save on databese from model function.
This is my controller
public function addStockSizes(Request $request)
{
if ($request->isMethod('post')) {
$this->validate($request, [
'size' => 'required',
]);
$data['size'] = $request->input('size');
$data['netSize'] = $request->input('net_size');
$data['mouseText'] = $request->input('mouse_text');
Stock_size::createSize($data);
return redirect()->back()->with('success', true)->with('message',
'Size is successfully added');
} else {
$sizes = Stock::all();
return view('admin.StockSize.addStockSizes', compact('sizes'));
}
}
And this is my function in model
public static function createSize($data)
{
$size = $data['size'];
$netSize = $data['netSize'];
$mouseText = $data['mouseText'];
$model = new self();
$model->size = $size;
$model->net_size = $netSize;
$model->mouse_text = $mouseText;
$model->save();
}
You can use the create function on an Eloquent model. This function expects an associative array with the data for the database.
Stock_size::create($request->only(['size', 'net_size', 'mouse_text']));
Keep in mind that you might get a MassAssignmentException because model properties are guarded against this by default. This can be fixed by adding the fields that are inserted to the $fillable array of your model:
protected $fillable = ['size', 'net_size', 'mouse_text'];

Save object with foreign keys in laravel

I use PHP, Laravel 5.2 and MySQL.
During user registration, I need to create a new Patient. But, Patient has user id, contact id and guardian id(foreign keys).
When I try to save() the patient, I get the following exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'patient_id' in
'field list' (SQL: update users set patient_id = 0, updated_at =
2016-06-07 12:59:35 where id = 6)
The problem is that I DO NOT have patient_id column. Instead I have patientId.
I don't know how to fix this issue. Any help will be appreciated. I can include the migration files if this is important.
UserController.php
public function postSignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:100',
'password' => 'required|min:6'
]);
$guardian = new Guardian();
$guardian->guardianId = Uuid::generate();;
$guardian->save();
$contact = new Contact();
$contact->contactId = Uuid::generate();
$contact->save();
$user = new User();
$user->email = $request['email'];
$user->name = $request['name'];
$user->password = bcrypt($request['password']);
$user->save();
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
$patient->contact()->save($contact);
$patient->guardian()->save(guardian);
$patient->save();
Auth::login($user);
// return redirect()->route('dashboard');
}
Patient.php
class Patient extends Model
{
protected $primaryKey='patientId';
public $incrementing = 'false';
public $timestamps = true;
public function user()
{
return $this->hasOne('App\User');
}
public function contact()
{
return $this->hasOne('App\Contact');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
public function allergies()
{
return $this->belongsToMany('App\PatientToAllergyAlert');
}
public function medicalAlerts()
{
return $this->belongsToMany('App\PatientToMedicalAlert');
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function patient()
{
return $this->belongsTo('App\Patient');
}
}
Contact.php
class Contact extends Model
{
protected $table = 'contacts';
protected $primaryKey = 'contactId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
Guardian.php
class Guardian extends Model
{
protected $table = 'guardians';
protected $primaryKey = 'guardianId';
public $timestamps = true;
public $incrementing = 'false';
public function contact()
{
return $this->belongsTo('App\Patient');
}
}
You have not defined relationships correctly. First of all, fill in table fields into $fillable array in Patient, Contact, Guardian classes (just like in User class).
If you want to use hasOne relationship between Patient and User, you're gonna need user_id field on patients table. You can alternatively use belongsTo relationship.
If you want to use custom column names, just specify them in relationship methods:
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
// alternatively
return $this->belongsTo('App\User', 'user_id', 'id');
}
Just go through documentation without skipping paragraphs and you will get going in a few minutes :)
https://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Also, this will not work:
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->user()->save($user);
new Patient() only creates the object, but does not store it in DB, so you will not be able to save relationships. You need to create the object and store it to DB to avoid this problem:
$patient = Patient::create(['patientId' => (string)Uuid::generate()]);
$patient->user()->save($user);
...
// or
$patient = new Patient();
$patient->patientId = (string)Uuid::generate();
$patient->save();
$patient->user()->save($user);
...
When you're setting up your relationship, you can to specify the name of the primary key in the other model. Look here.
I'm not sure, but I think you relationships are not defined properly.

Laravel 3 - Eloquent query returns rules

I'm trying to send use models for the first time and running into a confusion. When I run a query, the rules are linked with it, is it supposed to be like that?
Model:
class User extends Elegant
{
public static $table = 'users';
protected $rules = array(
'email' => 'required|email',
'firstname' => 'required',
'lastname' => 'required',
'initials' => 'required|alpha|match:/[A-Z]+/',
'role' => 'required|in:writer_fr,writer_en,reader',
'password' => 'min:6,max:32|same:password2'
);
public static function has_role($role)
{
//$u = new User;
$users = User::where($role, '=', 1)->get(array('firstname', 'lastname'));
return $users;
}
}
Controller
$u = array();
$u['writer_en'] = User::has_role('writer_en');
dd($u['writer_en']);
Which prints out the entire model rules, messages, relationship etc logic. Am I doing something wrong or is this normal?
In your has_role method you are returning User model
public static function has_role($role)
{
//$u = new User;
$users = User::where($role, '=', 1)->get(array('firstname', 'lastname'));
return $users; // <-- User model
}
So, it's dumping the User model and it's doing the right thing as it suppose to do by following code
$u = array();
$u['writer_en'] = User::has_role('writer_en');
dd($u['writer_en']);
Instead of dumping the model, you can use
$user = User::has_role('writer_en');
echo $user->firstname;
echo $user->lastname;

Categories