Unable to get, insert data from Database with codeigniter 4 - php

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.

Related

CREATE operation with Eloquent ORM shows 500 internal server error

I am trying to make a POST request to add a showroom in the Laravel application. When I try to do it with Showroom model using Eloquent ORM , it shows 500 internal server error. But if I do it with DB query, then it successfully CREATE the showroom. I commented out the db query lines and apply dd debugging and found out table for Showroom Model is null.
This is my controller code -
public function store(ShowroomRequest $request)
{
$showroom = new Showroom([
"name" => $request->get('name'),
"address" => $request->get('address'),
"description" => $request->get('description'),
]);
dd($showroom);
$ret = $showroom->save();
// $name = $request->input('name');
// $address = $request->input('address');
// $description = $request->input('description');
// DB::table('showroom')->insert(
// ['name' => $name, 'address' => $address, 'description' => $description]
// );
return redirect()->route('back.showroom.index')->withSuccess(__('Showroom Added Successfully.'));
}
And this is my model -
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Showroom extends Model
{
protected $fillable = ['name', 'description', 'address'];
protected static $ordersModel = 'App\Models\Order';
protected static $reviewsModel = 'App\Models\Review';
public function Orders()
{
return $this->hasMany(static::$ordersModel, 'showroom_id');
}
public function Reviews()
{
return $this->hasMany(static::$reviewsModel, 'showroom_id');
}
}
Finally this is my db structure -
Can anyone help me to find out what went wrong here? Thanks in advance.
in controller can you assign static values instead of request->get, and see if it saves.
please let me what happens afterwards.
also assign name of table in model like this,
protected $table = 'tablename';

CodeIgniter 4 delete Post Method

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');
}

Laravel: Too few arguments to function App\Status::create(), 1 passed and exactly 2 expected

I have two models (Categories and Channels) in a Morph Relation with Status (active, inactive).
In the moment of creating a new category or a new Channel I need to assign the active status to the new created element. For that, I need to pass the $type (channel or category) and the id of the "statusable" element.
Here is my CategoryController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\CategoriesRequest;
use App\Profile;
use App\Status;
use Session;
use Auth;
class CategoriesController extends Controller
{
public function store(CategoriesRequest $request)
{
$category = Category::create([
'title' => $request->title,
'slug' => str_slug($request->title, '-'),
'about' => $request->about,
]);
$category->save();
$type = 'categories';
$id = $category->id;
$status = (new Status)->create($id, $type); <-- Hier I am passing the two variables to the function CREATE in Status Model
Session::flash('success', 'Category successfully created!');
return redirect()->route('categories.show', $category->slug);
}
}
And hier the STATUS Model with the CREATE method which receive the two variables
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Status;
Relation::morphMap([
'channels' => 'App\Channel',
'categories' => 'App\Category',
]);
class Status extends Model
{
protected $fillable = [
'status',
'statusable_type',
'statusable_id',
];
public function statusable()
{
return $this->morphTo();
}
public static function create($id, $type)
{ // I do hier dd($id); and dd($type) and the two variables have a value
$status = Status::create([
'statusable_id' => $id,
'statusable_type' => $type,
'status' => 'active', // I get the error here!
]);
$status->save();
return $status;
}
}
I confirmed that the two variables arrived to the CREATE method (I see then if I dd() it) right at the beginning of the method. However two lines after I get this error:
Type error: Too few arguments to function App\Status::create(), 1 passed in C:\laragon\www\streets\app\Status.php on line 41 and exactly 2 expected
What am I doing wrong?
EDIT: I have got myself the solution:
If anybody is interested
I have changed the call in Controller to:
$type = 'categories';
$id = $category->id;
Status::create_status($id, $type);
and then in Status model:
public static function create_status($id, $type)
{
$status = new Status;
$status->statusable_id = $id;
$status->statusable_type = $type;
$status->status = 'active';
$status->save();
return $status;
}

Fractal parseIncludes not working

I'm using the Laravel framework for my web app, eloquent models for data and Fractal to transform some data.
I want to use the parseIncludes functionality of fractal but I can't seem to get it working despite following the docs.
Here's my code:
StudentTransformer.php
class StudentTransformer extends Fractal\TransformerAbstract
{
protected $availableIncludes = [
'course'
];
public function transform(Student $student)
{
return [
'name' => $student->name,
// other attributes
];
}
public function includeCourse(Student $student)
{
$course = $student->course;
return $this->item($course, new CourseTransformer);
}
}
CourseTransformer.php
class CourseTransformer extends Fractal\TransformerAbstract
{
public function transform(Course $course)
{
return [
'name' => $course->name
// other attributes
];
}
}
In one of my controllers:
$student = App\Models\Student::first();
$fractal = new \League\Fractal\Manager();
$fractal->parseIncludes('/student?include=course');
$fractal->setSerializer(new \League\Fractal\Serializer\ArraySerializer());
$response = new \League\Fractal\Resource\Item($student, new \App\Transformers\Models\StudentTransformer);
return response()->json($fractal->createData($response)->toArray());
Also, when I remove the availableIncludes from the StudentTransformer and use defaultIncludes instead, like so:
protected $defaultIncludes = [
'course'
];
It works just fine?! No idea why! Any help would be appreciated.
Fixed it. For the benefit of others, the issue was here:
$fractal->parseIncludes('/student?include=course');
It should just be:
$fractal->parseIncludes('course');

How to pass and retrieve data between two controllers in Laravel

I'm trying to get to grips with Laravel and not finding the documentation any help at all. It seems to assume you know so much instead of actually walking new users through each section step by step.
I've got to the point where I need to make an internal call to another class, and sticking with MVC I can't seem to do what should be a simple thing.
My code:
class UsersController extends BaseController {
protected $layout = 'layouts.templates.page';
protected $messages;
public function getIndex()
{
$input = array('where', array('field' => 'email', 'operator' => '=', 'value' => 'tony#fluidstudiosltd.com'));
$request = Request::create('user/read', 'GET');
$users = json_decode(Route::dispatch($request)->getContent());
var_dump($users); exit;
$this->pageTitle = 'Fluid Customer Status :: Admin Users';
$this->content = View::make('layouts.admin.users');
}
}
Class UserController extends Base Controller
public function getRead()
{
$userId = (int) Request::segment(3);
if ($userId)
{
$user = User::findOrFail($userId);
return $user;
}
else
{
$users = new User;
var_dump(Input::all()); exit;
if (Input::has('where'))
{
var_dump(Input::get('where')); exit;
}
return $users->get();
}
}
Why isn't the input data from UsersController#getIndex available in UserController#getRead

Categories