Laravel Slug Duplicate - mysql

when i trying to create post with the same slug it create post normally also in update the same problem
in this case i'v duplicate slugs for post
i search a lot about this problem but i didn't get any answers
any idea to solve this problem ?
Model
protected $fillable = [
'title', 'slug', 'body',
];
Controller
public function slug($string, $separator = '-') {
if (is_null($string)) {
return "";
}
$string = trim($string);
$string = mb_strtolower($string, "UTF-8");;
$string = preg_replace("/[^a-z0-9_\sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
$string = preg_replace("/[\s-]+/", " ", $string);
$string = preg_replace("/[\s_]/", $separator, $string);
return $string;
}
public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $this->slug($request->slug);
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('content.admin.post.index', ['url' => Post::find($id)]);
else {
$rules = [
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts,slug,{$post->slug},slug',
'body' => 'required',
];
$this->validate($request, $rules);
$post = Post::find($id);
$post->title = $request->title;
$post->slug = $this->slug($request->slug);
$post->body = $request->body;
$post->save();
return redirect('/admin/posts');
}
}

Preform your transformations on the slug field before passing it to the validator.
public function store(Request $request)
{
$request->slug = $this->slug($request->slug);
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|min:3|max:255|unique:posts',
'body' => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}

Why not just set slug column as unique in database migration?
Like this:
$table->string('slug')->unique();

Related

Edit records CodeIgniter

I'm developing a basic crud application using PHP Codeigniter 3 with MySQL database.
I have done add and list method successfully but now I want to edit the record and have included an edit button in the records table in view. when I click on the button it will go to my edit record view but it shows some errors. I checked everything but I fail to resolve it.
This is my controller
<?php
class User extends CI_controller
{
public function index()
{
$this->load->model('User_model');
$users = $this->User_model->getUsers();
// print_r($users);
$data = array();
$data['users'] = $users;
$this->load->view('users/list',$data);
}
public function create()
{
//load model here
$this->load->model('User_model');
//load library
$this->load->library('form_validation');
$this->load->library('ckeditor');
$this->load->library('ckfinder');
//set rules
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('projectname', 'Projectname', 'required');
$this->form_validation->set_rules('projecttype', 'Projecttype', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('projectdescription', 'Projectdescription', 'required');
// $this->form_validation->set_rules('termname', 'Termname', 'required');
// $this->form_validation->set_rules('termdescription', 'Termdescription', 'required');
$this->form_validation->set_rules('article_description', 'Article_description', 'required');
if ($this->form_validation->run() == true) {
// print_r($_POST);
// Array ( [name] => muhammad zawish [projectname] => test [projecttype] => Hardware [phone] => 03206270391 [email] => muhammadzawish#gmail.com [address] => Gondal Road, Sialkot, Punjab, Pakistan [projectdescription] => aaaaaaaaaa [termname] => aaaaaa [termdescription] => aaaaaaaa )
$name = $this->input->post('name');
$projectname = $this->input->post('projectname');
$projecttype = $this->input->post('projecttype');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$projectdescription = $this->input->post('projectdescription');
// $termname = $this->input->post('termname');
// $termdescription = $this->input->post('termdescription');
$article_description = $this->input->post('article_description');
// $formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'termname' => $termname, 'termdescription' => $termdescription,);
$formData = array('name' => $name, 'projectname' => $projectname, 'projecttype' => $projecttype, 'phone' => $phone, 'email' => $email, 'address' => $address, 'projectdescription' => $projectdescription, 'article_description' => $article_description);
//ck editor files
$this->ckeditor->basePath = base_url() . 'asset/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array('Source', '-', 'Bold', 'Italic', 'Underline', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', '-', 'NumberedList', 'BulletedList')
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor, '../../asset/ckfinder/');
$this->User_model->add_user($formData);
$this->session->set_flashdata('message', 'Record has been added successfully');
redirect(base_url('user/index'));
} else {
$this->load->view('users/create');
}
}
function edit($id){
$this->load->model('User_model');
$row = $this->User_model->getUser($id);
$data1 = array();
$data1['row'] = $row;
$this->load->view('users/edit', $data1);
}
}
this is my model
<?php
class User_model extends CI_Model{
public function add_user($formArray){
// $this->load->library('session');
$this->db->insert('users', $formArray);
}
//for view data fetch from database
public function getUsers(){
$users = $this->db->get('users')->result_array();
return $users;
}
//for edit record
function getUser($id){
$this->db->where('id', $id);
$row = $this->db->get('users')->row_array();
return $row;
}
}
?>
when I access my edit.php view
404 Page Not Found
The page you requested was not found.

MySQL doesn't update properly

I am trying to update status for users. code works fine .but it can't update in DB
controller.php
public function update_customer(Request $request)
{
$sid = 1;
$setting['setting'] = Settings::editGeneral($sid);
$site_max_image_size = $setting['setting']->site_max_image_size;
$name = $request->input('name');
$username = $request->input('username');
$email = $request->input('email');
$user_type = $request->input('user_type');
$status =$request->input('status');
$data = array('name' => $name, 'username' => $username, 'email' => $email, 'user_type' => $user_type, 'password' => $pass, 'earnings' => $earnings, 'user_photo' => $user_image,'status'=>$status, 'updated_at' => date('Y-m-d H:i:s'));
Members::updateData($token, $data);
return redirect($page_url)->with('success', 'Update successfully.');
}
}
model.php
public static function updateData($token,$data){
DB::table('users')
->where('user_token', $token)
->update($data);
}
how to solve it??
You can use Model class instead of DB Facade. Like below:
User.php
protected $fillable = [
'name' , 'username' , 'email' , 'user_type' , 'password' , 'earnings' , 'user_photo' ,'status', 'updated_at'
];
public static function updateData($token,$data)
{
User::where('user_token', $token)
->update($data);
}

How can I valid random names fields in Yii?

I have a lot of fields generated from loops. I would like to validate them through validation rules (integer). I don't know how to throw so many fields with random names into the model to the rules () function. How can I validate fields without a model?
View:
<?= Html::input('number', 'file[' . $indexRow . ']' . '[' . $indexCell . ']', $cell, $options = ['class' => 'form-control', 'filter' => 'intval', 'integer']) ?>
Controller:
` public function actionEdit($fileName)
{
$siteHelper = new SiteHelper();
$editForm = new EditForm();
$preparedRows = $siteHelper->prepareRows($fileName);
$preparedHTML = '';
if (Yii::$app->request->isPost) {
$post = Yii::$app->request->post();
if (isset($post['file'])) {
$dataFile = $post['file'];
$preparedRows = $siteHelper->updateExcelFile($fileName, $dataFile);
Yii::$app->session->setFlash('success', 'Plik został zaktualizowany!');
} else if (isset($post['EditForm'])) {
$events = $post['EditForm']['events'];
$preparedHTML = $siteHelper->prepareHTML($events, $preparedRows, $fileName);
Yii::$app->session->setFlash('success', 'Wygenerowano plik PDF!');
}
}
$viewParameters = [
'rows' => $preparedRows,
'editForm' => $editForm,
'scoreHTML' => $preparedHTML,
'downloadLink' => Url::toRoute(['site/download', 'fileName' => $fileName])
];
return $this->render('edit', $viewParameters);
}`
Model:
`
class EditForm extends Model
{
public $events;
public function rules()
{
return [
[['events'], 'required'],
['events', 'integer'],
];
}
}`
When you have an array you can use each validator:
https://www.yiiframework.com/doc/api/2.0/yii-validators-eachvalidator
The validation function should be:
public function rules()
{
return [
[['events'], 'each', 'rule' => ['required']],
[['events'], 'each', 'rule' => ['integer']],
];
}
You may need to avoid multidemnsional array in html and render the field like this:
<?= Html::input('number', 'file[' . $indexRow . '-' . $indexCell . ']', $cell, $options = ['class' => 'form-control', 'filter' => 'intval', 'integer']) ?>
later you can "explode" the row cell index (isn't it supposed to be col?) to identify the row and the column.
$rowCellIndecies = explode('-', $rowCellIndex);
explode function: https://www.php.net/manual/en/function.explode.php

Inserting variables in Yii2 to Database

I am trying to insert $product, $pric and $user to database table cart. Following is the function that I have created in SiteController.php.
public function actionCartadd($id)
{
$product = Additem::find()
->select('product')
->where(['id' => $id])
->one();
$pric = Additem::find()
->select('price')
->where(['id' => $id])
->one();
$user = Yii::$app->user->identity->username;
$connection = Yii::$app->getDb();
$result = Yii::$app->db->createCommand()
->insert('cart', [
'product' => '$product',
'price' => '$pric',
'user' => '$user',
])->execute();
if ($result)
return $this->render('custstore');
}
However, this end up in error. Can anyone suggest any fix
Try this following code
$result = Yii::$app->db->createCommand()->insert('cart', [
'product' => $product->product,
'price' => $pric->price,
'user' => $user
])->execute();
Look at this fragment:
'product' => '$product',
'price' => '$pric',
'user' => '$user',
Use double quotes in values or just variables without quotes
Also, better way to fetch product and price:
$productItem = Additem::findOne($id);
if ($productItem instanceof Additem) {
$product = $productItem->product;
$pric = $productItem->price;
}

cant import data csv to database in yii2

I am very new to web development.
I'm newbie in here, my first question in stackoverflow..
i am confused what error on code, Code will be store data array csv to a database,
sorry my bad english.
Controller
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
Model
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
thanks for helping..
change your code to the following to output the errors which could happen when you try to save. Errors could occur depending on your model rules.
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
getErrors() from Api
A better approach is to use exceptions to throw and catch errors on your import. Depends if you want to skip csv lines on errors or not.
finally it working with change this $hasil = explode(";", $data);