How to put condition in Codeigniter 4 model - php

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

Related

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

Exception in laravel 5.8 : Trying to get property of non-object when trying to edit data

Recently I've started with Laravel 5.8 and I'm trying to make the edit button which will update the row from the database. and when the edit button click, Laravel raise an error like this
this is my Controller:
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',['book'->$book]);
}
public function UploadEdit(Request $request){
DB::table('books')->where('id_book',$request->id_book)->update([
'judul' => $request->judul,
'gambar' => $request->gambar,
'kategori' => $request->kategori,
'deskripsi' => $request->deskripsi,
'ketersediaan' => $request->ketersediaan,
'lokasi' => $request->lokasi
]);
return redirect()->back();
}
this is my models:
class Books extends Model
{
protected $table = "books";
protected $primaryKey = "id_book";
protected $fillable = [
'judul',
'gambar',
'kategori',
'deskripsi',
'ketersediaan',
'lokasi'
];
}
I was trying to solve this problem with change edit function in the controller:
from this
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',['book'->$book]);
}
to this
public function edit($id_book){
$book = Books::find($id_book);
return view('/books',compact('book'));
}
and this:
public function edit($id_book){
$book = Books::find($id_book);
return view('/books')->withBooks('$book');
}
but it doesn't work
I think error shows id_book is wrong.
You should use findOrFail() method.
public function edit($id_book){
$book = Books::findOrFail($id_book);
return view('/books',compact('book'));
}
Change your line 58 (edit() function's return statement) to:
return view('/books',compact('book'));
It seems you used -> instead => to assign value
Change
return view('/books',['book'->$book]);
to
return view('/books',['book' => $book]);
Try this
public function edit($id_book) {
$book = Book::find($id_book);
return view('books.edit', compact('book'));
}
Try this:
public function edit($id_book){
$book = Books::where('id_book', $id_book)->first();
return view('/books', compact('book'));
}

Saving array of dynamic fields data to DB using oneToMany relationship

I have been trying to save the data coming from the dynamically generated fields in the form of an array. I have a oneToMany relationship for the customer table.
I have tried to loop through each field but I am unable to achieve it, please correct me if I am wrong.
public function store(Request $request)
{
$res = $request->all();
$res['address'] = implode(' ', array_values($request->address));
$customer = Customer::create($res);
if ($res) {
$customerData = [];
foreach ($request->department_name as $key => $n) {
$customerData = array(
'department_name' => $request->department_name[$key],
'person_name' => $request->person_name[$key],
'person_number' => $request->person_number[$key],
'person_email' => $request->person_email[$key],
'notification_flag' => !isset($request->notification_flag[$key]) ? 0 : $request->notification_flag[$key] === "on" ? 1 : 0,
'custinvoice_noti' => !isset($request->outstanding[$key]) ? 0 : $request->outstanding[$key] === "on" ? 1 : 0,
'invoice_noti' => !isset($request->invoice[$key]) ? 0 : $request->invoice[$key] === "on" ? 1 : 0,
);
$deptModel[] = new Department($customerData);
$customer->department()->saveMany($deptModel);
}
}
return redirect('admin/customers');
}
Customer model and Department model have the following relationship.
class Customer extends Model
{
protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];
public function department()
{
return $this->hasMany('App\Department');
}
}
Department Model.
class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
public function store(Request $request)
{
$customer = new Customer();
$customer->owner_name = $request['owner_name'];
$customer->country = $request['country'];
$customer->state = $request['state'];
$customer->city = $request['city'];
$customer->pincode = $request['pincode'];
$customer->number = $request['number'];
$customer->correspondance_check = $request['correspondance_check'];
$res = $customer->save();
$cus = Customer::where(['id'=> $res->id])->firstOrFail();
$dep = new Department();
$dep->customer()->associate($cus);
$dep->save();
return redirect('admin/customers');
// return response()->json($customerData);
}
Customer model and Department model have the following relationship.
class Customer extends Model
{
protected $fillable = ['owner_name', 'address', 'country', 'state', 'city', 'pincode', 'number', 'correspondance_check'];
public function department()
{
return $this->hasMany('App\Department');
}
}
//Department Model.
class Department extends Model
{
protected $fillable = ['customer_id', 'department_name', 'person_name', 'person_number', 'person_email', 'notification_flag', 'notification_type'];
public function customer()
{
return $this->belongsTo('App\Customer');
}
}

how to get id of table in relationship to use in other table in this relation?

i have relation between Service and Services_Gallery one to many, and i want to use id of Service when i insert new image to Services_Gallery, and this is my Controller:
public function save(Request $request)
{
$this->validate($request,[
'image' => 'required|image|mimes:jpeg,jpg,png,svg|max:1024'
]);
$services_Gallery = new Services_Gallery();
$services_Gallery->image = $request->image->move('Uploads', str_random('6') . time() . $request->image->getClientOriginalName());
$services_Gallery->Service::all(id) = $request->service_id; //The problem here
$services_Gallery->save();
return back();
}
this is my Models:
class Service extends Model
{
protected $table = 'services';
protected $fillable = [
'en_main_title',
'ar_main_title',
'en_sub_title',
'ar_sub_title',
'en_content_title',
'ar_content_title',
'en_content',
'ar_content',
'priority',
];
public function gallery()
{
return $this->hasMany('App\Services_Gallery','service_id');
}
}
class Services_Gallery extends Model
{
protected $table = 'services_galleries';
protected $fillable = [
'image',
'service_id',
];
public function gallery(){
return $this->belongsTo('App\Service','service_id');
}
}
Exapmle:
$modelOfService = Service::where('param_x', $request->service_id)->first();
$id = $modelOfService->id;
Is that you need?

Laravel 5.4 How to responses JSON with Relationship?

I want to response JSON with Laravel that I have CategoryModel belongTo SongModel.
This is my CategoryModel
class CategoryModel extends Model
{
protected $table = 'categories';
protected $fillable = [
'id',
'name',
];
public function song()
{
return $this->hasMany(SongModel::class);
}
}
And this is my SongModel
class SongModel extends Model
{
protected $table = 'songs';
protected $fillable = [
'id',
'name',
'url',
'categories_id',
'singers_id',
'types_id',
];
public function category()
{
return $this->belongsTo(CategoryModel::class);
}
}
I want to response JSON with the relationship. I wrote:
class SongController extends Controller
{
public function index(SongModel $songModel)
{
$song = $songModel->category()->get();
return response()->json(["DATA" => $song], 201);
}
}
To do this you will just need to load the relationship before you return the response:
public function index(SongModel $songModel)
{
$songModel->load('category');
return response()->json(["DATA" => $songModel], 201);
}
https://laravel.com/docs/5.4/eloquent-relationships#lazy-eager-loading
Hope this helps!
Try this. return response()->json(["DATA" => $songModel->load('category')->toArray()], 201);
OR, you can use with('song')
lass SongController extends Controller
{
public function index(SongModel $songModel)
{
$song = $songModel::with('song')->get();
return response()->json(["DATA" => $song], 201);
}
}

Categories