Can't delete a record in Laravel 5 - php

I'm having trouble in deleting a record that has file in it. Below is the code.
delete file method :
private function deletePDF(Journal $journal) {
$exist = Storage::disk('file')->exists($journal->file);
if (isset($journal->file) && $exist) {
$delete = Storage::disk('file')->delete($journal->file);
if ($delete) {
return true;
}
return false;
}
}
Destroy method :
public function destroy(Journal $journal, EditionRequest $request) {
$this->deletePDF($journal);
$journal->delete();
return redirect()->route('edition', ['id' => $request->id]);
}
The result game me nothing, it's just return to the page where the record belongs and does not deleting the record. I used the same code for another project with the same laravel version and it's working, but for some reasons it doesn't work here and I'm a lil bit confused.
Update :
EditionRequest :
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
} else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}

If it returns to the same page as before, you probably have a validation error in your request!
You can check the errors easily by adding the following snippet to your view:
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
With this you should be able to see what's going wrong. Let me know if it worked :)
edit
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
}
else if($this->method() == 'DELETE'){
//your delete validation rules rules
$volume_rules = ''
$number_rules= '';
}
else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
You might even want to not use the request youre using now, which would give you this:
public function destroy(Journal $journal, Request $request)

Related

ArgumentCountError Too few arguments to function App\Controllers\Blog::view()

Sorry for my bad english but i have a problem when i try to open localhost:8080/blog this message show up
Too few arguments to function App\Controllers\Blog::view(), 0 passed in C:\xampp\htdocs\baru\vendor\codeigniter4\framework\system\CodeIgniter.php on line 896 and exactly 1 expected
so this is the controller:
use CodeIgniter\Controller;
use App\Models\ModelsBlog;
class Blog extends BaseController
{
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
public function form(){
$data = [
'title' => 'Edit Form'
];
helper('form');
return view('view_form', $data);
}
public function view($id){
$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('view',$data);
}
public function simpan(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->SimpanBlog($data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Simpan');
}
public function form_edit($id){
$data = [
'title' => 'edit artikel'
];
$model = new ModelsBlog();
helper('form');
$data['artikel'] = $model->PilihBlog($id)->getRow();
return view('form_edit',$data);
}
public function edit(){
$model = new ModelsBlog();
if ($this->request->getMethod() !== 'post') {
return redirect()->to('blog');
}
$id = $this->request->getPost('id');
$validation = $this->validate([
'file_upload' => 'uploaded[file_upload]|mime_in[file_upload,image/jpg,image/jpeg,image/gif,image/png]|max_size[file_upload,4096]'
]);
if ($validation == FALSE) {
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi')
);
} else {
$dt = $model->PilihBlog($id)->getRow();
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
$upload = $this->request->getFile('file_upload');
$upload->move(WRITEPATH . '../public/assets/blog/images/');
$data = array(
'judul' => $this->request->getPost('judul'),
'isi' => $this->request->getPost('isi'),
'gambar' => $upload->getName()
);
}
$model->edit_data($id,$data);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Ubah');
}
public function hapus($id){
$model = new ModelsBlog();
$dt = $model->PilihBlog($id)->getRow();
$model->HapusBlog($id);
$gambar = $dt->gambar;
$path = '../public/assets/blog/images/';
#unlink($path.$gambar);
return redirect()->to('./blog')->with('berhasil', 'Data Berhasil di Hapus');
}
}
ModelsBlog.php :
use CodeIgniter\Model;
class ModelsBlog extends Model
{
protected $table = 'artikel';
public function getArtikel()
{
return $this->findAll();
}
public function SimpanBlog($data)
{
$query = $this->db->table($this->table)->insert($data);
return $query;
}
public function PilihBlog($id)
{
$query = $this->getWhere(['id' => $id]);
return $query;
}
public function edit_data($id,$data)
{
$query = $this->db->table($this->table)->update($data, array('id' => $id));
return $query;
}
public function HapusBlog($id)
{
$query = $this->db->table($this->table)->delete(array('id' => $id));
return $query;
}
}
And this is the view.php:
<body style="width: 70%; margin: 0 auto; padding-top: 30px;">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2><?php echo $artikel->judul; ?></h2>
</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div class="row">
<?php
if (!empty($artikel->gambar)) {
echo '<img src="'.base_url("assets/blog/images/$artikel->gambar").'" width="30%">';
}
?>
<?php echo $artikel->isi; ?>
</div>
</div>
</div>
</body>
i cant find any solutions for this error, pls help thank you very much
Let's go over what you're telling the code to do.
First, you make a call to /blog. If you have auto-routing turned on this will put you forward to the controller named 'Blog'.
class Blog extends BaseController
And since you do not extend the URL with anything, the 'index' method will be called.
public function index()
{$data = [
'title' => 'artikel'
];
$model = new ModelsBlog();
if (!$this->validate([]))
{
$data['validation'] = $this->validator;
$data['artikel'] = $model->getArtikel();
return view('view_list',$data);
}
}
The index method sets $data to an array filled with 'title' => 'artikel'. And then fills $model with a new ModelsBlog.
class ModelsBlog extends Model
There is no __construct method defined in ModelsBlog so just the class is loaded and specific execution related to $model stops there, which is fine.
Then, the index() from Blog goes on and checks whether or not $this->validate([]) returns false. Since there's no else statement, if $this->validate([]) were to return true, code execution would stop there. So we'll assume $this->validate([]) returns false. So far so good, there's nothing weird going on with your code.
However, IF $this->validate([]) returns false, you tell the index() to return the function called view(). Normally CodeIgniter would serve you the view you set as the first parameter. But since you also have a Blog method named 'view', CodeIgniter will try to reroute te request to that method. So in other words, the actual request you're trying to make is:
Blog::view()
And since you've stated that view() receives 1 mandatory parameter, the requests triggers an error. You can solve the problem by either renaming the view() method of Blog to something like 'show()' or 'read()'. Anything else that does not conflict with the native CodeIgniter view() function would be good.
Honestly though, you are sending through two parameters in the index() function call so I'm slightly confused why the error generated states you provided 0, but I hope at least you gain some insight from my answer and you manage to fix the problem.
If anyone could provide more information regarding this, feel free to comment underneath and I'll add your information to the answer (if it gets accepted).

session lost after reloading in laravel 6

Here is simple sigin method :
LoginController :
public function signin(Request $r)
{
$data['email'] = $r->email;
$data['password'] = md5($r->password);
if ($data['email'] == '' || $data['password'] == '') {
echo 'Please enter email or password.';
} else {
$userInfo = DB::table('users')->where('email', $data['email'])->get()->first();
if ($data['email'] == $userInfo->email && $data['password'] == $userInfo->password) {
$r->session()->put('userData', $data['email']);
$userData = $r->session()->get('userData');
return redirect('/userpanel')->with('status', $userData);
} else {
return redirect('/login');
}
}
}
HomeController :
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
return view('userDashboard')->with(['data' => $data]);
}
After login this method redirects to the user panel here display the session information. But if I reload here there don't display any session information. In my blade I print session by the following code :
<div class="alert alert-success" class="d-block">
<div id="userEmail" >{{ session('status') }}</div>
</div>
I use it in HomeController and LoginController. But problem is not fix.
Using with you are basically Flashing Data To Session which will remain in session only for next request, that why when you reload you are not getting that that again.
https://laravel.com/docs/5.8/session#flash-data
This is with() implementation, in which it flashes data using flash(), which will be remain for just for next request.
public function with($key, $value = null)
{
$key = is_array($key) ? $key : [$key => $value];
foreach ($key as $k => $v) {
$this->session->flash($k, $v);
}
return $this;
}
Change this code
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
session(['data' => $data]);
return view('userDashboard');
}
Add this in your blade file.
#if(\Session::has('status'))
<span>{{\Session::get('status')}}</span>
#endif

capture user id when login and save user id based on operations

I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Unique key validation showing error while updating data in laravel

Hi I am creating an application using laravel and i have a model where asset_number field is unique and the validation rules are as follows
MODEL
protected $rules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{id}',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
Here is my controller code for create and edit
CONTROLLER
public function postCreate()
{
// get the POST data
$new = Input::all();
// create a new Assetdetail instance
$assetdetail = new Assetdetail();
// attempt validation
if ($assetdetail->validate($new))
{
// Save the location data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function getEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
//$assetlife = DB::table('asset_details')->where('id', '=', $assetdetailId)->lists('asset_life');
$location_list = array('' => '') + Location::lists('name', 'id');
$assettype_list = array('' => '') + Assettype::lists('asset_type', 'id');
$assignTo_list = array('' => 'Select a User') + User::select(DB::raw('CONCAT(first_name, " ", last_name) AS full_name'), 'id') ->lists('full_name', 'id');
$assetdetail_options = array('' => 'Top Level') + DB::table('asset_details')->where('id', '!=', $assetdetailId)->lists('asset_number', 'id');
return View::make('backend/assetdetails/edit', compact('assetdetail'))->with('assetdetail_options',$assetdetail_options)->with('location_list',$location_list)->with('assettype_list',$assettype_list)->with('assignTo_list',$assignTo_list);
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.does_not_exist'));
}
$new = Input::all();
/*if ($assetdetail ->asset_number == Input::old('asset_number') &&
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
}*/
if ($assetdetail->validate($new))
{
// Update the asset data
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
else
{
// failure
$errors = $assetdetail->errors();
return Redirect::back()->withInput()->withErrors($errors);
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
My Route.php
Route::post('create', array('as' => 'savenew/assetdetail','uses' => 'Controllers\Admin\AssetdetailsController#postCreate'));
Route::get('{assetdetailId}/edit', array('as' => 'update/assetdetail', 'uses' => 'Controllers\Admin\AssetdetailsController#getEdit'));
Route::post('{assetdetailId}/edit', 'Controllers\Admin\AssetdetailsController#postEdit');
Now the problem is whenever i try to update my form my asset_number field throws an Error: The asset_number has already been taken.How do i pass the id in my controller while updating my form so that it throws error only if an already existing asset_number is used and not while editing the form with current asset_number.
I tried the following with no luck
Model
'asset_number' => 'mobileNumber' => 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Controller
Assetdetail::$rules['mobileNumber'] = 'required|min:5|numeric|unique:asset_details,asset_number,' . $id
Hi i finally found a working solution myself here is what i did please take a look
Controller
class AssetdetailsController extends AdminController
{
protected $validationRules = array
(
'asset_number' => 'required|alpha_dash|min:2|max:12|unique:asset_details,asset_number',
'asset_name' => 'alpha_space',
'asset_type_id' => 'required',
'shift' => 'required',
);
public function postCreate()
{
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
// attempt validation
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
// Was the asset created?
if($assetdetail ->save())
{
// Redirect to the new location page
return Redirect::to("admin/settings/assetdetails")->with('success', Lang::get('admin/assetdetails/message.create.success'));
}
}
// Redirect to the location create page
return Redirect::to('admin/settings/assetdetails/create')->with('error', Lang::get('admin/assetdetails/message.create.error'));
}
public function postEdit($assetdetailId = null)
{
// Check if the location exists
if (is_null($assetdetail = Assetdetail::find($assetdetailId)))
{
// Redirect to the blogs management page
return Redirect::to('admin/settings/assetdetails')->with('error', Lang::get('admin/assetdetails/message.assetdetail_not_exist'));
}
$this->validationRules['asset_number'] = "required|alpha_dash|min:2|max:12|unique:asset_details,asset_number,{$assetdetail->asset_number},asset_number";
$validator = Validator::make(Input::all(), $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
else
{
$assetdetail ->asset_number = e(Input::get('asset_number'));
$assetdetail ->asset_name = e(Input::get('asset_name'));
$assetdetail ->asset_type_id = e(Input::get('asset_type_id'));
$assetdetail ->shift = e(Input::get('shift'));
if($assetdetail->save())
{
// Redirect to the saved location page
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('success', Lang::get('admin/assetdetails/message.update.success'));
}
}
// Redirect to the asset management page with error
return Redirect::to("admin/settings/assetdetails/$assetdetailId/edit")->with('error', Lang::get('admin/assetdetails/message.update.error'));
}
}

Categories