how to connect to tables to a table in laravel - php

It is so long that I have been dealing with this but no result have I achieved yet. So I decided to ask for your help.
I have 3 tables => article, category and country and I want to connect these tables.
Each category can have multiple articles but each article is related to only one category.
Each country can have multiple articles but each article is related to only one country.
The problem is with the ArticleController part which works for connecting only one table to article but for connecting both tables to it, I receive this error:
SQLSTATE[HY000]: General error: 1364 Field 'country_id' doesn't have a default value
and also I have country_id and category_id as my foreign keys in articles table.
Below are my tables:
article model:
public function countries(){
return $this->belongsTo('App\country');
}
public function categories(){
return $this->belongsTo('App\category');
}
country model
public function articles(){
return $this->hasMany('App\Article');
}
category model
public function articles(){
return $this->belongsToMany('App\Article');
}
ArticleController - and the main part = the problem
public function store(Request $request)
{
$article = new article(
[
'title' => $request->input('title'),
'top_content' => $request->input('top_content'),
'quote' => $request->input('quote'),
'left_content' => $request->input('left_content'),
'right_content' => $request->input('right_content'),
]
);
if ($request->hasFile('article_slider_image')) {
$file = time() . '_' . $request->file('article_slider_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleSliderImages';
$request->file('article_slider_image')->move($destination, $file);
$article->article_slider_image = $file;
}
if ($request->hasFile('left_image')) {
$file = time() . '_' . $request->file('left_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleLeftImages';
$request->file('left_image')->move($destination, $file);
$article->left_image = $file;
}
if ($request->hasFile('right_image')) {
$file = time() . '_' . $request->file('right_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleRightImages';
$request->file('right_image')->move($destination, $file);
$article->right_image = $file;
}
$country = country::where('name',$request->input('country'))->first();
$category = category::where('name',$request->input('category'))->first();
//$article->category_id = 1; //not commenting this part works fine
$country->articles()->save($article);
$category->articles()->save($article);// but when I use this one, it gives me error
//dd($category->id);
$article->save();
return redirect()->route('article.index')->with('success', 'article created successfully' . $request->title);
}
I will really appreciate if someone helps.

You don't need to load the whole model to save an article, you just need an id, therefore:
$article->country_id = country::where('name',$request->input('country'))->pluck('id')->first();
$article->category_id = category::where('name',$request->input('category'))->pluck('id')->first();
And finally
$article->save();

SQLSTATE[HY000]: General error: 1364 Field 'country_id' doesn't have a
default value
The above error means whenever your are inserting data to database,you are not passing value of country_id and database searching default value and you have not assigned default value for country_id in db table.
Try this, i have assigned value to country_id and category_id before saving the article
public function store(Request $request)
{
$article = new article(
[
'title' => $request->input('title'),
'top_content' => $request->input('top_content'),
'quote' => $request->input('quote'),
'left_content' => $request->input('left_content'),
'right_content' => $request->input('right_content'),
]
);
if ($request->hasFile('article_slider_image')) {
$file = time() . '_' . $request->file('article_slider_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleSliderImages';
$request->file('article_slider_image')->move($destination, $file);
$article->article_slider_image = $file;
}
if ($request->hasFile('left_image')) {
$file = time() . '_' . $request->file('left_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleLeftImages';
$request->file('left_image')->move($destination, $file);
$article->left_image = $file;
}
if ($request->hasFile('right_image')) {
$file = time() . '_' . $request->file('right_image')->getClientOriginalName();
$destination = base_path() . '/public/images/articleRightImages';
$request->file('right_image')->move($destination, $file);
$article->right_image = $file;
}
$country = country::where('name',$request->input('country'))->first();
$category = category::where('name',$request->input('category'))->first();
$article->country_id = $country->id;
$article->category_id = $category->id;
$article->save();
return redirect()->route('article.index')->with('success', 'article created successfully' . $request->title);
}

SQLSTATE[HY000]: General error: 1364 Field 'country_id' doesn't have a default value
in this error you can easily see country_id doesn't have a default
it means whenever your are inserting data to data base it is not passing any data and database searching default value
so you code your be
if(!$country){
return redirect()->route('article.index')->with('error', 'country not found.');
}
$article->country_id = $country->id;
$article->category_id = $category->id;
$article->save();

Related

How to update master and detail form in laravel?

I have this code in controller to update the data from database :
public function update(Request $request, $id)
{
$anodizing = Anodizing::find($id);
$anodizing->date= $request->date;
$anodizing->number= $request->number;
$anodizing->item_total = $request->item_total;
$anodizing->desc= $request->desc;
if ($request->hasFile('picture')) {
$anodizing_image = public_path("uploads/reports/anodizing/{$anodizing->picture}");
if (File::exists($anodizing_image)) {
File::delete($anodizing_image);
};
$file = $request->file('picture');
$extension = $file->getClientOriginalExtension();
$filename = $request->number. '-' . date('YmdHms') . '.' . $extension;
$file->move('uploads/reports/anodizing', $filename);
$anodizing->picture= $filename;
}
$anodizing->save();
$id = $anodizing->id;
foreach ($request->addmore as $key => $value) {
$anodizingdetail = AnodizingDetail::find($value['id']);
$anodizingdetail->aluminium_id= $value['name'];
$anodizingdetail->qty = $value['qty'];
$anodizingdetail->weight= $value['weight'];
$anodizingdetail->save();
}
Basically this update method works perfectly to update or edit existing data, but the problem is, what to do if I want to edit and then insert a new row in the detail form ?
I'm aware of updateorCreate method in laravel, is that the right method ? How to use that ? or I need to use something else ?
as you said, instead of AnodizingDetail::find use findOrNew
docs: https://laravel.com/docs/master/eloquent-relationships#the-create-method

Column in table not getting updated but not showing error

Hello everyone I'm getting confused because when I'm running a code with some condition only 1 column getting updated and the others column stay null, I'm sure there is no typo with the column name in table nor in code here is my code :
public function solusi_line($id)
{
$idasli = base64_decode($id);
$solusi = solusi::where('request_id', $idasli)->orderBy('created_at', 'asc')->get();
$count = solusi::where('request_id', $idasli)->orderBy('created_at', 'desc')->count();
$cekakun = Session::get('id');
$adminkah = Admin::where('user_id', $cekakun)->count();
// dd($solusi);
//jika admin ke bagian sini
if ($adminkah != 0) {
# code...
return view('admin.detail_feedback', compact('solusi', 'count'));
} else {
return view('user.detailfeedback_user', compact('solusi', 'count'));
}
//klo user kebagian user
}
public function FirstFeedback($id)
{
$datas = Kirim::where('id', $id)->first();
return view('admin.detailprogress', compact('datas'));
}
//solusi dari admin
public function solusiPost(Request $request)
{
$itungsolusi = solusi::where('request_id', $request->idRequest)->count();
$data = new solusi();
$data->request_id = $request->idRequest;
$data->pengirim_id = Session::get('id');
$data->penerima_id = $request->idPenerima;
$data->solusi = $request->solusi;
$file = $request->file('lampiran_solusi');
if (!empty($file)) {
$ext = $file->getClientOriginalExtension();
$name = time() . '.' . $ext;
$file->move('upload/lampiran/', $name);
$data->lampiran = $name;
$data->url_lampiran = url('upload/lampiran') . "/" . $name;
} else {
$data->lampiran = null;
$data->url_lampiran = null;
}
if ($data->save()) {
//matiin sementara
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
$id_solusi = $data->id;
$thisUser = DB::table('kirims')
->join('simpan_users', 'kirims.pengirim_id', '=', 'simpan_users.user_id')
->join('solusis', 'kirims.id', '=', 'solusis.request_id')
->where('kirims.id', $data->request_id)
->where('solusis.id', $id_solusi)
->select('kirims.email', 'kirims.ticket_id', 'solusis.solusi', 'solusis.lampiran', 'solusis.url_lampiran')
->first();
// dd($thisUser);
here the problem
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
I really appreciate for any help, I getting stuck because laravel not showing error too, thank you.
You should check your Kirim model, where you need to define $fillable property. Something like below.
class Kirim extends Model {
protected $fillable = ['remarks', 'status', 'status_feedback',''];
// All fields inside $fillable array can be mass-assigned
}
use update statement like this.
$user->remarks = 'Ya',
$user->status = 'CheckByUser',
$user->status_feedback = 'Ya'
$user->update();
few days ago i faced the same issue and fixed it as i told you .

zend update is deleting old values

I am doing update in zend which in some cases doesn't update all the fields, the fields that are not updated become null as if we are doing an add.
This is the code from the Controller
$result = $theuserModel->updateUserTest(
$id,
$this->getRequest()->getPost('user_name'),
/*some code*/
$this->getRequest()->getPost('user_postee')
);
if ($result) {
$this->view->notif = "Successfull Update";
return $this->_forward('index');
}
The corresponding model
public function updateUserRest($id, $nom,$poste)
{
$data = array(
'user_name' => $nom,
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
I do an update for user_name only I found that the old value of user_postee got deleted and replaced by the default value (initial value which we get at the time of creation) for example null.
Thanks in advance!
I have done this changes (bad solution) If anyone has another one optimised
->Controller
if($this->getRequest()->getPost('user_name')){
$resultname=$userModel->updateUserName($id,$this-
>getRequest()->getPost('user_name'));
}
if($this->getRequest()->getPost('user_postee')){
$resultpostee=$userModel->updateUserPoste($id,$this-
>getRequest()->getPost('user_postee'));
}
if ($resultname|| $resultpostee){
$this->view->notif = "Mise à jour effectuée";
return $this->_forward('index');
}
-> Model
public function updateUserName($id, $name)
{
$data = array(
'user_name' => $name
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
public function updateUserPostee($id, $postee)
{
$data = array(
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
that is complete correct response of update in Zend Db Table.
I believe your assumption is if the value of 'user_postee' is null then it should not be updated into the database, am I correct.
The answer is they will update the new value of "NULL" into the database.
To avoid it , what you should do is
using fetchrow() to get the value of the line by id
foreach user_name and user_postee check if the value of them matching the array value your fetched , if nothing changed or Null, then use the old value from array , if new value exist use new value insert into the array , finally use update to update the new array into database
Assume your Table Column is also "user_name" and "user_postee"
public function updateUserRest($id, $nom,$poste)
{
$row = $this->fetchRow('user_id = '. (int)$id);
if(!empty($nom) && $row['user_name'] != trim($nom)){
$row['user_name'] = $nom;
}
if(!empty($poste) && $row['user_poste'] != trim($poste)){
$row['user_poste'] = $poste;
}
$result=$this->update($row, 'user_id = '. (int)$id);
return $result;
}

Laravel 5.4 from 5.3 : Error getOtherKey()

I was getting the relationship as in laravel 5.3 and was working fine:
//execute the relation of the given model
$data = $model->{$info["relation"]}();
// get the type of the relation
$class = get_class($data);
$dataType = explode("\\", $class);
$relationType = end($dataType);
$options["columns"][$key]["relationType"] = $relationType;
// if its a simple belongs-to statement
if($relationType == "BelongsTo") {
// get all belongs-to query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getQualifiedForeignKey();
$otherKey = $data->getOtherKey();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $otherKey, '=', $foreignKey);
} else if($relationType == "HasMany" || $relationType == "HasOne") {
// get all has-many query info
$otherTable = $data->getRelated()->getTable();
$foreignKey = $data->getPlainForeignKey();
$parentKey = $data->getQualifiedParentKeyName();
// manually join using it
$retrievedRecords->leftJoin($otherTable . ' as ' . $info["relation"], $info["relation"] . '.' . $foreignKey, '=', $parentKey);
}
Now i downloaded fresh laravel 5.4 and it gives me error :
Call to undefined method Illuminate\Database\Query\Builder::getOtherKey()
As the getOtherKey() exists in the above code in if() section.
Is there any alternative for that ?
The getOtherKey method has been renamed to getOwnerKey. So you can get the owner key by saying:
$ownerKey = $data->getOwnerKey();

PHP failed to load string from other function as parameter

public function test_passing_string() {
$this - > load - > model(array('registration/Registration_model', 'Jawaban_lab_model'));
$registration = new Registration_model();
$jawaban_lab = new Jawaban_lab_model();
$id = "kuda4";
$jawaban_lab - > load($id); //load jawaban_lab from id
$manualy_written_registration_number = "REG/FM/130102-0001";
echo "registration number from jawaban_lab->registration_number : ".$jawaban_lab - > registration_number
.
"<br> registration number from manualy_written_registration_number : ".$manualy_written_registration_number;
//$registration->load($jawaban_lab->registration_number);
$registration - > load($manualy_written_registration_number);
echo "<br> patient id : ".json_encode($registration - > PatientID);
}
Before go to the question, I will explain my code.
On test_passing_string() function, I call 2 model, and create object for each model there are $registration and $jawaban_lab.
To load data from model I create a load() function. load() has two parameters: column_value and column_name. The default value for column_name is that model's Primary Key.
BUT
The problem comes from
$registration->load($jawaban_lab->registration_number);
I can't retrieve any $registration object data, then I test it by passing the value manually by write this:
$manualy_written_registration_number = "REG/FM/130102-0001";
$registration - > load($manualy_written_registration_number);
And the result appear, doesn't that mean my load() function is fine?
Then I check value inside $jawaban_lab->registration_number by echoing it, surprisingly it display same value as my $manualy_written_registration_number variable.
This is screenshoot in my browser when I run test_passing_string() function:
Using $manualy_written_registration_number value
Using $jawaban_lab->registration_number value
Why can't I use the value from
$jawaban_lab->registration_number even though it has the same value as
my manually writen registraiton number?
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
I use multiple database using CodeIgniter 3, registration_model from SQL server and jawaban_lab from MySQL, jawaban lab have column registration_number to store registration_model primary key
var_dump
First of all thanks to rlanvin and Nirajan N Raju
from rlanvin's comment, i find out the problem is come from codeigniter's query helper, because when i enable codeigniter profiling sql server query return "SELECT CASE WHEN (##OPTIONS | 256) = ##OPTIONS THEN 1 ELSE 0 END AS qi"
so i think codeigniter might be cannot generate query so i create the query manually
i change
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
to this
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $column_name . " LIKE '" . trim($column_value) . "'");
} else {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $this::DB_TABLE_PK . " LIKE '" . trim($column_value) . "'");
}
if ($query->row()) {
$this->populate($query->row());
}
}

Categories