How to make update data of mysql in laravel - mysql

I'm trying to make an update with values from a form and pass it into an update controller using a route, there's no error given but why there's nothing happen after I updated the data?
Form:
<form action="/update" id="frm_edit" method="post" enctype="multipart/form-data">
Routes:
Route::post('/update', 'EditManga#update'); //update route
Route::post('/admin_page/manga_list', 'Add_Manga_Controller#upload')->name('upload.image');
Route::get('/admin_page/manga_list','ShowData#Manga_list');
Controller:
public function update(Request $request){
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
$judul = $request->input('jdmanga');
$alternatif = $request->input('almanga');
$author = $request->input('aumanga');
$status = $request->status;
$lastup = $request->input('lumanga');
$genre = $request->input('grmanga');
$lastc = $request->input('lcmanga');
$sinopsis = $request->input('sinopsis');
$file = $request->file('image');
DB::table('add_manga')->where('kode_manga',$kode_manga)->update([
'judul_manga' => $judul,
'alt_title' => $alternatif,
'author' => $author,
'status' => $status,
'uploaded' => $lastup,
'genre' => $genre,
'latest' => $lastc,
'summary' => $sinopsis
]);
return redirect('/admin_page/manga_list');
}
}
is there any other way or there something's wrong with my code?, Thank you.

In you scenario this another of doing this:
public function update(Request $request, $id)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpg,png,jpeg'
]);
//MENGAMBIL FILE IMAGE DARI FORM
$kode_manga = $request->input('kdmanga');
//getting the target row to updae
$addmanga = DB::table('add_manga')->select('*')
->where('kode_manga',$kode_manga)->get();
$id = $addmanga->id; // getting the id of the target
$add_manga = App\YOUR_MODEL_NAME::find($id);
$add_manga->judul_manga = $request->input('jdmanga');
$add_manga->alt_title = $request->input('almanga');
$add_manga->author = $request->input('aumanga');
$add_manga->status = $request->status;
$add_manga->uploaded = $request->input('lumanga');
$add_manga->genre = $request->input('grmanga');
$add_manga->latest = $request->input('lcmanga');
$add_manga->summary = $request->input('sinopsis');
$add_manga->file = $request->file('image');
$add_manga->save();
return redirect('/admin_page/manga_list');
}
Hope this will work for you!

Related

How to retrive from other table and input it again into another table in laravel?

I want to retrieve some data from 'tbl_karyawan' and input into 'tbl_absen' which is if the NIP exist from 'tbl_karyawan' then parshing some data into 'tbl_absen'. I was create the code, and the data is going well. but i have something trouble with
i want the data input in Nip_kyn be like 'KIP001' not [{"Nip_kyn":"KIP001"}].
this is my Model
public function presensi($data)
{
$isExist = DB::table('tbl_karyawan')
->where('Nip_kyn', $data)->exists();
if ($isExist) {
$namakyn = DB::table('tbl_karyawan')->where($data)->get('Nama_kyn');
$nippppp = DB::table('tbl_karyawan')->where($data)->select('Nip_kyn')->get($data);
$values = array('Nip_kyn' => $nippppp, 'Nama_kyn' => $namakyn, 'Jam_msk' => now(), 'Log_date' => today());
DB::table('tbl_absen')->insert($values);
} else {
echo 'data not available';
}
}
this is my controller
public function get()
{
$day = [
'time_in' => $this->AbsenModel->timeIN(),
'time_out' => $this->AbsenModel->timeOut(),
'break' => $this->AbsenModel->break(),
// absen here
's' => $this->AbsenModel->absensi(),
];
$data = [
'Nip_kyn' => Request()->Nip_kyn,
];
$this->AbsenModel->presensi($data);
return view('v_absen', $data, $day);
}
Yup, I finally got it, the problem is on my model.
$nama_karyawan = DB::table('tbl_karyawan')->where($data)->value('Nama_kyn');
$nipkyn = DB::table('tbl_karyawan')->where($data)->value('Nip_kyn');
I just change 'get' to 'value'.

How to add picture to database with laravel

I am creating Laravel 7 project and I want to add/browse images into/from MySQL database.
The images column names are icon_lg and icon_sm
This is my create function in the Controller I tried it in two ways as I saw in some tutorials:
public function create(Request $request)
{
$object = $this->objectModel::create([
'name' => $request->name,
'icon_sm' => $request->icon_sm
]);
if($request->hasFile('icon_lg')) {
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
It does nothing with icon_lg it inserts null value to it.
And it deals with icon_sm as String.
i think you must set the hasfile validation inside foreach loop like
$images = explode(',', $request->hasFile('icon_lg'));
foreach($images as $image)
if($request->hasFile('icon_lg')) {
$filename = rand().'.'.$image->getClientOriginalExtension();
$filePath = public_path("images");
$image->move($filePath, $filename);
return Image::create([
'icon_lg' => $filename,
//'item_id' => $created->id,
]);
}
just test it without validation first
it should work

Make FileInput Optional for user in Yii2

I have a file Input field in my form which works good to upload the file. But I want to keep the provision for user that they might not upload any file at all.
My Code looks like below -
Model Rule -
[['jha'],'file','skipOnEmpty' => true,'extensions' => 'pdf'],
Form
<?= $form->field($model, 'jha')->fileInput(['accept' => 'application/pdf']); ?>
Controller -
public function actionCreatenewworkbasic()
{
$model = new Workpermit();
$model->wp_timeissued = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()))
{
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}else{
return $this->renderAjax('createnewworkbasic', [
'model' => $model,
]);
}
}
By this code, If I leave the upload field untouched, I get error -
Call to a member function saveAs() on null
Check empty before saveAs()
if ($model->load(Yii::$app->request->post())) {
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}

Yii2 - Integrity constraint violation – yii\db\IntegrityException

I have a rather weired error on trying to add data to my database. It keeps telling me that there is an Integrity violation, i.e.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ticketing_system`.`parcels`, CONSTRAINT `FK_parcels_customers_customer_id` FOREIGN KEY (`sender_id`) REFERENCES `customers` (`customer_id`))
The SQL being executed was: INSERT INTO `parcels` (`parcel_id`) VALUES (DEFAULT)
I have checked the values being inserted and all of them are picked from the referenced table. Funny bit is that when I echo the values and use them to update the database directly via SQL query on the PHPMyAdmin, the database is populated well without any problem. Again, when I try to change the order of the foreign keys as they appear on the SQL query being performed, the first one fails, meaning all the foreign keys of the model are failing.
EDITED
Here is my actionCreate in the ParcelsController
public function actionCreate()
{
$model = new Parcels();
$customerModel = new Customers();
//checking whether we are getting the logged in user id value
Yii::info("User id=".Yii::$app->user->id);
$model->received_by_id = Yii::$app->user->id;
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post('Customers');
$sender_id = Customers::create([
'name' => $data['name'],
'mobile_number' => $data['mobile_number'],
'sex' => $data['sex'],
'address' => $data['address'],
'registered_by_id' => $model->received_by_id,
]);
$data = Yii::$app->request->post('Parcels');
$receiver_id = Customers::create([
'name' => $data['name'],
'mobile_number' => $data['mobile_number'],
'sex' => $data['sex'],
'address' => $data['address'],
'registered_by_id' => $model->received_by_id,
]);
$model->consignment_number = $model->generateUniqueRandomString("consignment_number");
$model->source_id = $model->receivedBy->station_id;
$model->parcel_id = Parcels::create([
'consignment_number' => $model->consignment_number,
'sender_id' => $sender_id,
'receiver_id' => $receiver_id,
'source_id' => $model->source_id,
'destination_id' => $data['destination_id'],
'type_id' => $data['type_id'],
'weight' => $data['weight'],
'cost' => $data['cost'],
'parcel_info' => $data['parcel_info'],
'received_by_id' => $model->received_by_id,
]);
// return $this->redirect(['view', 'id' => $model->parcel_id]);
} else {
return $this->render('create', [
'model' => $model, 'customerModel' => $customerModel,
]);
}
}
Customers::create function in the Customers Model
public static function create($data)
{
$model = new self;
$mobile_number = $data['mobile_number'];
$exists = $model->find()->where( [ 'mobile_number' => $mobile_number ] )->exists();
if($exists) {
$existing_customer = Customers::find()
->where('mobile_number = :mobile_number', [':mobile_number' => $mobile_number])
->one();
return $existing_customer['customer_id'];
}
else {
$model->name = $data['name'];
$model->registered_by_id = $data['registered_by_id'];
$model->mobile_number = $data['mobile_number'];
$model->sex = $data['sex'];
$model->address = $data['address'];
$model->status = 10;
$model->save();
return $model->getPrimaryKey();
}
}
Parcels::create function in the Parcels Model
public static function create($data)
{
$model = new self;
$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];
$model->save(false);
return $model->getPrimaryKey();
// echo var_dump($data);
// echo "Consignment Number: ".$consignment_number." - Sender: ".$sender_id." - Receiver: ".$receiver_id." - From: ".$source_id." - To: ".$destination_id." - Type: ".$type_id." - Weight: ".$weight." - Cost: ".$cost." - Parcel Info: ".$parcel_info." - Received By: ".$received_by_id;
}
And here is the function generateUniqueRandomString() in the Parcels Model
public function generateUniqueRandomString($attribute, $length = 10) {
$randomString = Yii::$app->getSecurity()->generateRandomString($length);
$randomString = strtoupper($randomString);
if(!$this->findOne([$attribute => $randomString]))
return $randomString;
else
return $this->generateUniqueRandomString($attribute, $length);
}
Sorry for bothering you guys. I was able to get the problem of where I was going wrong. In the create() function of the Parcels Model, I only created new variables and failed to bind them to the model, i.e.
$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];
Should have been:
$model->consignment_number = $data['consignment_number'];
$model->weight = $data['weight'];
$model->cost = $data['cost'];
$model->parcel_info = $data['parcel_info'];
$model->received_by_id = $data['received_by_id'];
$model->status = $data['status'];
$model->receiver_id = $data['receiver_id'];
$model->sender_id = $data['sender_id'];
$model->source_id = $data['source_id'];
$model->destination_id = $data['destination_id'];
$model->type_id = $data['type_id'];
Sorry for taking your time because of my carelessness.

Silverstripe: Convert twitter JSON string to Dataobject to loop though in template

I'm using the twitter API to get a timeline which I want to output through my template. I'm getting the feed like so:
public static function getTwitterFeed(){
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx",
'consumer_key' => "xxx",
'consumer_secret' => "xxx"
);
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=xxx&count=5';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$returnTwitter = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
return json_decode($returnTwitter);
}
This returns an array of objects (the tweet is the object) and I want to be able to loop through it in my template like so:
<% loop TwitterFeed %>
<h4>$created_at</h4>
<p>$text</p>
<% end_loop %>
As I have it above, the loop is entered once but no values are recognised. How can I achieve this?
DataObjects in SilverStripe represent a record from the database, in your case you wound use a ArrayData.
Use $array = Convert::json2array($returnTwitter) or $array = json_decode($returnTwitter, true) instead.
and see https://stackoverflow.com/a/17922260/1119263 for how to use ArrayData
Thanks to Zauberfisch for pointing me in the right direction. I solved it like so:
public static function getTwitterFeed(){
$settings = array(
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx",
'consumer_key' => "xxx",
'consumer_secret' => "xxx"
);
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=xxx&count=5';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$returnTwitter = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$returnTwitter = Convert::json2array($returnTwitter);
$tweets = array();
foreach ($returnTwitter as $key => $value) {
$tweets[] = new ArrayData(array('created_at' => $value['created_at'], 'text' => $value['text']));
}
return new ArrayList($tweets);
}