CodeIgniter 4 delete Post Method - php

Good Day all
before this get removes i must note that i have tried searching for this but i still cant understand why this is not working
Please can someone help me with this i tried doing this for a few weeks now and i cannot figure out why my delete button does not work i did it on the code igniter3 and it work but i canot seem to get it to work as i am still learning and is new all i want to do is delete a post with a button that i have created ! that all please explain what i did wrong so i can learn this is just a test project to teach myself code igniter 4 thank you so much
sorry for my bad english
so here is my code
Model (Newsmodel.php)
<?php
namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
protected $table = 'news';
protected $allowedFields = ['title', 'slug', 'body'];
public function getNews($slug = false)
{
if ($slug === false) {
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
here is Controller(News.php)
<?php
namespace App\Controllers;
use App\Models\NewsModel;
use CodeIgniter\Controller;
class News extends Controller
{
public function index()
{
$model = new NewsModel();
$data = [
'news' => $model->getNews(),
'title' => 'News archive',
];
echo view('templates/header', $data);
echo view('news/overview', $data);
echo view('templates/footer', $data);
}
public function view($slug = null)
{
$model = new NewsModel();
$data['news'] = $model->getNews($slug);
if (empty($data['news'])) {
throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item: ' . $slug);
}
$data['title'] = $data['news']['title'];
echo view('templates/header', $data);
echo view('news/view', $data);
echo view('templates/footer', $data);
}
public function create()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required',
])) {
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', true),
'body' => $this->request->getPost('body'),
]);
echo view('news/success');
} else {
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
}
View(view.php)
<h2><?=esc($news['title'])?></h2>
<p><?=esc($news['body'])?></p>
<button>Delete</button>
i have tried the following in my controller
and it didint delete it from my database but i also did not get an error! it just redirects me to my succes page.
public function delete($id = null)
{
$model = new NewsModel();
$model->delete([
$model->where('id', $id)->delete(),
]);
return view('news/delete');
}
i have also tried this
public function delete()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post') {
$model->delete([
'title' => $this->request->getPost('title'),
'body' => $this->request->getPost('body'),
]);
echo view('news/delete');
}
DB set up
DB NAME= toets
TABLE= news
id|title|slug|body

i changed my view button to
Delete
and in my controller i made
public function delete($id)
{
$model = new NewsModel();
$model->where('id', (int) $id)->delete();
return view('news/delete');
}

Related

Unable to get, insert data from Database with codeigniter 4

I am trying the new codeigniter 4
Trying to create first app following tutorial
https://codeigniter.com/user_guide/tutorial/news_section.html
My controller method to insert data
public function create()
{
$model = new NewsModel();
if (! $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
])) {
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
} else {
$model->save([
'title' => $this->request->getVar('title'),
'slug' => url_title($this->request->getVar('title'), '-', true),
'body' => $this->request->getVar('body'),
]);
echo view('news/success');
}
}
It is echoing success page but data not inserting into database.
In .env file I used
database.default.hostname = localhost
database.default.database = news_db
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
I think db connection working as checked with wrong database details its not working
My model is
<?php namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
protected $table = 'news';
protected $allowedFields = ['title', 'slug', 'body'];
public function getNews($slug = false)
{
if ($slug === false) {
return $this->findAll();
}
return $this->asArray()
->where(['slug' => $slug])
->first();
}
}
The error is most likely coming from your Model declaration in the Controller.
$model = new NewsModel();
It should be namespaced.
Try:
$model = new \App\Models\NewsModel();
or
$model = model('NewsModel');
I am suggesting that:
if you haven't you should follow the tutorial strictly by extending the core controller because you did not show that in your code.
use CodeIgniter\Controller;
class News extends Controller
And You didnt use App\Models\NewsModel;
Before instantiating your Model class. You can only do that in the way Ali-coder illustrate.
Again still suggesting you should have use
$request->getPost()
Instead of $this->request->getVar('title')
I am suggesting all this because that is how i wrote mine and it work fine.

How to put condition in Codeigniter 4 model

I have this model in Codeigniter 4.
class CommentsModel extends Model
{
protected $table = 'comments';
protected $allowedFields = ['com_user', 'com_email', 'com_phone', 'comment'];
}
and this route
public function comments()
{
$model = new CommentsModel();
$data = [
'comments' => $model->paginate(50),
'pager' => $model->pager
];
echo view('templates/header');
echo view('templates/aside');
return view('comments', $data);
echo view('templates/footer');
}
I want to put condition WHERE so that this will get only comments that meet with the condition....Please help!
Use Where clause in active records to get what you want.
public function comments()
{
$model = new CommentsModel();
$model = $model->where('com_user','john');
$data = [
'comments' => $model->paginate(50),
'pager' => $model->pager
];
echo view('templates/header');
echo view('templates/aside');
return view('comments', $data);
echo view('templates/footer');
}

What is the best way to return validation messages with Phalcon PHP as json

I'm creating REST API, and I want to return messages from validation.
Here is example with user register:
class Users extends Phalcon\Mvc\Model {
public function validation() {
$validator = new Validation();
$validator->add('email', new PresenceOf([
'message' => 'The email is required'
]));
$validator->add('email', new Email([
'message' => 'Invalid email given'
]));
$validator->add('email', new Uniqueness([
'message' => 'Sorry, The email was registered by another user'
]));
return $this->validate($validator);
}
Here is my current code:
class UserController extends Phalcon\Mvc\Controller {
public function register() {
$data = $this->request->getJsonRawBody();
$user = new Users();
$user->setEmail($data->email)->setUsername($data->username)->setPassword($data->password);
if ($user->save() === false) {
$data = [];
$messages = $user->getMessages();
foreach ($messages as $message) {
$data[] = array(
'field' => $message->getField(),
'type' => $message->getType(),
'message' => $message->getMessage()
);
}
return $this->response->setStatusCode(409, 'Conflict')->setJsonContent(array('error' => $data));
}
return $this->response->setStatusCode(201, 'Created')->setJsonContent(array('message' => "User id:" . $user->getId() . " created"));
}
When I change this for loop with something like that I get empty response:
return $this->response->setStatusCode(409, 'Conflict')->setJsonContent(array('error' => $user->getMessages()));
The question is it possible make this code shorter without loop trough messages, but just simple return json object.
You can do it with very little modifications by extending default methods. Here is a working sample of your code:
// BaseModel class which overwrites default Phalcon methods if needed.
class BaseModel extends \Phalcon\Mvc\Model
{
public function getMessagesNormalized()
{
$messages = parent::getMessages();
$data = [];
foreach ($messages as $message) {
$data[] = array(
'field' => $message->getField(),
'type' => $message->getType(),
'message' => $message->getMessage()
);
}
return $data;
}
}
// Note that your models from now on extend BaseModel which extends \Phalcon\Mvc\Model
class Users extends BaseModel {
// ...
}
// Your controller
class UserController extends Phalcon\Mvc\Controller {
public function register() {
$data = $this->request->getJsonRawBody();
$user = new Users();
$user->setEmail($data->email)->setUsername($data->username)->setPassword($data->password);
if ($user->save() === false) {
$data = [];
// Get the messages in RESTsuitable format
$messages = $user->getMessagesNormalized();
return $this->response->setStatusCode(409, 'Conflict')->setJsonContent(array('error' => $data));
}
return $this->response->setStatusCode(201, 'Created')->setJsonContent(array('message' => "User id:" . $user->getId() . " created"));
}

Cake 3 PHP error while with adding articles in CMS tutorial

I've got a problem with CMS Tutorial for Cake 3, it was going fine until I've added Auth component.
Now, no matter what user I use to add new article it always results in error 'Unable to add your article.'
This is how my ArticlesController looks like:
<?php
namespace App\Controller;
class ArticlesController extends AppController
{
//Wyświetla wszystkie artykuły
public function index()
{
$this->loadComponent('Paginator');
$articles = $this->Paginator->paginate($this->Articles->find());
$this->set(compact('articles'));
}
//Wyświetla pojedynczy artykuł na podstawie sluga
public function view($slug = null)
{
$article = $this->Articles->findBySlug($slug)->firstOrFail();
$this->set(compact('article'));
}
//Dodawanie artykułu
public function add()
{
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$article = $this->Articles->patchEntity($article, $this->request->getData());
$article->user_id = $this->Auth->user('id');
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add your article.'));
}
//Pobiera listę tagów dzięki połączeniu Many to Many w ArticlesTable
$tags = $this->Articles->Tags->find('list');
//Ustawia tagi do widoku
$this->set('tags', $tags);
$this->set('article', $article);
}
//Edycja artykułu
public function edit($slug)
{
$article = $this->Articles->findBySlug($slug)->contain('Tags')->firstOrFail();
if ($this->request->is(['post', 'put'])) {
$this->Articles->patchEntity($article, $this->request->getData(), [
// Added: Disable modification of user_id.
'accessibleFields' => ['user_id' => false]
]);
if ($this->Articles->save($article)) {
$this->Flash->success(__('Your article has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your article.'));
}
//Pobiera listę tagów dzięki połączeniu Many to Many w ArticlesTable
$tags = $this->Articles->Tags->find('list');
//Ustawia tagi do widoku
$this->set('tags', $tags);
$this->set('article', $article);
}
//Usuwanie Artykułu
public function delete($slug)
{
$this->request->allowMethod(['post', 'delete']);
$article = $this->Articles->findBySlug($slug)->firstOrFail();
if ($this->Articles->delete($article)) {
$this->Flash->success(__('The {0} article has been deleted.', $article->title));
return $this->redirect(['action' => 'index']);
}
}
//Wyszukiwanie artykułu po tagach
public function tags()
{
// The 'pass' key is provided by CakePHP and contains all
// the passed URL path segments in the request.
$tags = $this->request->getParam('pass');
// Use the ArticlesTable to find tagged articles.
$articles = $this->Articles->find('tagged', [
'tags' => $tags
]);
// Pass variables into the view template context.
$this->set([
'articles' => $articles,
'tags' => $tags
]);
}
public function isAuthorized($user)
{
$action = $this->request->getParam('action');
// The add and tags actions are always allowed to logged in users.
if (in_array($action, ['add', 'tags'])) {
return true;
}
// All other actions require a slug.
$slug = $this->request->getParam('pass.0');
if (!$slug) {
return false;
}
// Check that the article belongs to the current user.
$article = $this->Articles->findBySlug($slug)->first();
return $article->user_id === $user['id'];
}
public function initialize()
{
parent::initialize();
// Allow the tags
$this->Auth->allow(['tags']);
} }
I've tried to not miss any steps, but I still don't know why it won't work. Editing is just fine, it checks what user added article and it allow to edit to him.
Any ideas, or is it Cake 3 bug?

"Undefined variable" in laravel 5.2 view

I'm getting a undefined variable error in my view if I include this route with a parameter:
<div class="table-toolbar">
<div class="row">
<div class="col-md-6">
<div class="btn-group">
<i class="fa fa-plus"></i> Add new
</div>
</div>
</div>
</div>
Here's my full controller for that given view:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Model\CampusMajor;
use App\Model\CampusMajorsFacilities;
class CampusMajorsFacilitiesController extends Controller
{
//
public function index($campusMajorId)
{
$campusMajorsFacilities = CampusMajorsFacilities::ofCampusMajor($campusMajorId)->get();
$data = [
'campusMajorsFacilities' => $campusMajorsFacilities,
'campusMajor' => $campusMajorId
];
return view('major-facilities.index', $data);
}
public function add($campusMajorId)
{
$campusMajorsFacilities = new CampusMajorsFacilities;
$data = [
'campusMajorsFacilities' => $campusMajorsFacilities,
'campusMajorId' => $campusMajorId,
'formIs' => 'add'
];
return view('major-facilities.form', $data);
}
public function save(Request $request,$campusMajorId)
{
$this->validation($request);
$post = $request->all();
$campusMajorsFacilities = $this->bindToObject($post,$campusMajorId);
$campusMajorsFacilities->save();
return redirect()->route('major-facilities.index', $campusMajorId)->with('message','Item added Succesfully');
}
public function edit($campusMajorId, $id)
{
$campusMajorsFacilities = CampusMajorsFacilities::find($id);
$data = [
'campusMajorsFacilities' => $campusMajorsFacilities,
'campusMajorId' => $campusMajorId,
'formIs' => 'edit'
];
return view('major-facilities.form', $data);
}
public function update(Request $request,$campusMajorId,$id)
{
$this->validation($request);
$post = $request->all();
$campusMajorsFacilities = $this->bindToObject($post,$campusMajorId,$id);
$campusMajorsFacilities->save();
return redirect()->route('major-facilities.index', $campusMajorId)->with('message','Item updated Succesfully');
}
private function validation($request)
{
$this->validate($request,[
'title' => 'required',
'description' => 'required',
'content' => 'required',
'campus_major_id' => 'required'
]);
}
public function delete($campusMajorId,$id)
{
$campusMajorsFacilities = CampusMajorsFacilities::find($id);
$campusMajorsFacilities->delete();
return redirect()->route('major-facilities.index', $campusMajorId)->with('message','Item deleted Succesfully');
}
private function bindToObject($post,$campusMajorId,$id=null)
{
if(is_null($id)){
$campusMajorsFacilities = new CampusMajorsFacilities;
} else {
$campusMajorsFacilities = CampusMajorsFacilities::find($id);
}
$campusMajorsFacilities->major_campus_id = $campusMajorId;
$campusMajorsFacilities->title = $post['title'];
$campusMajorsFacilities->description = $post['description'];
$campusMajorsFacilities->content = $post['content'];
return $campusMajorsFacilities;
}
}
And my model
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class CampusMajorsFacilities extends Model
{
//
use SoftDeletes;
public function CampusMajor()
{
return $this->belongsTo('App\Model\CampusMajor');
}
public function scopeOfCampus($query, $campus_id)
{
return $query->where('campus_id', $campus_id);
}
public function scopeOfCampusMajor($query, $campus_major_id)
{
return $query->where('campus_major_id', $campus_major_id);
}
}
If I comment out the route I passed the view just fine, I don't know where I went wrong.
You have passed $campusMajorId from controller to view as campusMajor only, not as campusMajorId.
Hence the variable is undefined in the view.

Categories