I'm trying to publish post with user that register in my app, but this error happened:
And I'm using XAMPP and my posts table is this picture
And this error is in phpMyAdmin:
My PostController is:
use App\Post;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth')->except(['index','show']);
}
public function index()
{
$posts=Post::latest()->get();
return view('posts.index',compact('posts'));
}
public function show(Post $post)
{
return view('posts.show',compact('post'));
}
public function create()
{
return view('posts.create');
}
public function store()
{
$this->validate(request(),[
'title'=>'required',
'body' => 'required|min:5'
]);
Post::create(request([
'title' => request('title'),
'body' => request('body'),
'user_id' =>auth()->id()
//auth()->user()->id*/
]));
return redirect()->home;
}
}
and Post Model:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
It seems your store method is wrong.
Try something like this:
public function store()
{
$this->validate(request(),[
'title'=>'required',
'body' => 'required|min:5'
]);
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' =>auth()->id()
]);
return redirect()->home;
}
This code works for you?
INSERT into posts (title, body, userId) VALUES ('My title', 'My body', 7)
The first part specifies the field name, the second part specifies the values you are inserting into each field. 'My title' isn't the field you are inserting info into, it's shown as title.
Also, createdon uses timestamp so you don't need to include that. Updated on could insert a current timestamp once a record is changed.
<?php
if (isset($_POST['submit']))
{
include('../dbcon.php');
$rolno= $_POST['rollno'];
$name= $_POST['name'];
$city= $_POST['city'];
$pcon= $_POST['pcon'];
$std= $_POST['std'];
$imagename= $_FILES['simg'] ['name'];
$tempname= $_FILES['simg'] ['tmp_name'];
move_uploaded_file($tempname,"../dataimg/$imagename");
$qry= "SELECT * FROM `student` WHERE `rollno`='$rolno' AND `name`='$name'";
//$qry="INSERT INTO `student`(`rollno`, `name`, `city`, `pcont`, `standerd`,`image`) VALUES ('$rolno','$name','$city','$pcon','$std','$imagename')";
echo "$qry";
$run= mysqli_query($con,$qry);
if ($run == true)
{
?>
<script>
alert('Data Inserted Successfully.');
</script>
<?php
}
}
?>
Related
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');
}
So the problem is that when I try to update my entity it finds it updates it but gets stuck in a loop probably and doesn't exit. When I check the database, even before the 60 seconds of execution time that I have expires, the values that I have changed are updated.
If i constantly refresh (and here is where it gets crazy) the updated at values for other lectures starts to change every second while it executes this loop.
When creating (not finding the id on the condition It creates it without a problem)
I have Lectures which looks like this:
class Lecture extends Model
{
use Searchable;
use SoftDeletes;
protected $primaryKey = 'id';
protected $touches = ['themes', 'educationTypes', 'subjects'];
protected $fillable= [
'name', 'description', 'user_id', 'field_id', 'approved'
];
public static function boot()
{
parent::boot();
static::saved(function ($model) {
$model->themes->filter(function ($item) {
return $item->shouldBeSearchable();
})->searchable();
});
}
public function user(){
return $this->belongsTo('App\User')->with('companies');
}
public function geographies(){
return $this->belongsToMany('App\Geography');
}
public function educationTypes(){
return $this->belongsToMany('App\EducationType', 'lecture_education_type')->withTimestamps();;
}
public function themes(){
return $this->belongsToMany('App\Theme','lecture_theme', 'lecture_id', 'theme_id')->withTimestamps();;
}
public function subjects(){
return $this->belongsToMany('App\Subject', 'lecture_subject')->withTimestamps();;
}
public function cases(){
return $this->belongsToMany(
'App\CompanyCase' ,
'case_company_lecture',
'lecture_id',
'case_id',
'id',
'id')->withTimestamps();
}
public function companies(){
return $this->belongsToMany(
'App\Company' ,
'case_company_lecture',
'lecture_id',
'company_id',
'id',
'id'
);
}
public function field(){
return $this->belongsTo('App\Field');
}
public function toSearchableArray()
{
$this->themes;
$this->user;
$this->educationTypes;
$this->subjects;
$this->geography;
return $this->toArray();
}
}
This is the controller:
public function storeLecture(Request $request) {
$lecture_id = $request->get('lecture_id');
// It gets stuck between the comments
$lecture = Lecture::updateOrCreate(['id' => $lecture_id],
[
'name'=> request('name'),
'description'=> request('description'),
'user_id'=> request('user_id')]
);
// and doesn't update the themes, edu types subjects and etc.
$company_id = $request->get('company_id');
$company = Company::find(request('company_id'));
$lecture->companies()->sync([$company->id]);
$eduTypes= $request->get('education_types');
$themes= $request->get('themes');
$subjects = $request->get('subjects');
$geographies = $request->get('geographies');
$lecture->themes()->sync($themes);
$lecture->educationTypes()->sync($eduTypes);
$lecture->subjects()->sync($subjects);
$lecture->geographies()->sync($geographies);
$n1 = new Notification();
$n1->send(request('user_id'), 1, 'new_lecture', $lecture->id);
$user = User::where('id', $request->id)->first();
$user_with_companies = $user->load('companies');
$slug = $user_with_companies->companies->first()->slug;
return response(['success' => true]);
}
This is the frontend method sending the request (in between I have a middleware checking if the user is admin (possible to create a lecture) based on the this.selectedExpert.id, which doesn't interfere).
createUpdateLecture() {
const url = `${window.location.origin}/lecture/create/${
this.selectedExpert.id
}`;
this.$http
.post(url, {
education_types: this.allEducationTypes
.filter(el => el.checked)
.map(a => a.id),
themes: this.allThemes.filter(el => el.checked).map(a => a.id),
geographies: this.allGeographies
.filter(el => el.checked)
.map(a => a.id),
subjects: this.allSubjects.filter(el => el.checked).map(a => a.id),
name: this.lecture.name,
description: this.lecture.description,
user_id: this.selectedExpert.id,
company_id: this.company.id,
lecture_id: this.lecture.id
})
.then(res => {
console.log(res);
this.$parent.showLectureCreateModal = false;
// window.location.reload();
});
}
As I can see what is happening I probably use the method really badly but I just want to understand it better for further usage.
After a few days of researching and testing it turns out that it is not the updateOrCreate method causing the problem because I tried with two different functions for creating and updating and the update function was still having the same problem.
The problem is created from Algolia which is used for searching based on different fields in the platform. Fx. in Themes
class Theme extends Model
{
use SoftDeletes;
use Searchable;
protected $touches = ['lectures'];
public function lectures(){
return $this->belongsToMany('App\Lecture');
}
public function toSearchableArray()
{
$this->lectures;
return $this->toArray();
}
}
Removing the searchable from the models did the trick!
When I'm trying to update post it's updated successfully but, when it returns it shows error here-
NB: Replies under this post where I'm trying to update.
public function show($slug)
{
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = $discussion->replies()->where('best_answer', 1)->first();
return view('discussions.show')
->with('d', $discussion)
->with('best_answer', $best_answer);
}
Edit and Update
public function edit($slug)
{
return view('discussions.edit', ['discussion'=> Discussion::where('slug', $slug)->first()]);
}
public function update($id)
{
$this->validate(request(),[
'title' => 'required',
'content' => 'required'
]);
$d = Discussion::find($id);
$d->title = request()->title;
$d->content = request()->content;
$d->save();
Session::flash('success', 'Discussion updated');
return redirect()->route('discussion', ['slug', $d->slug]);
}
I have a function for adding a comment:
public function addComment(Request $request)
{
$request->validate([
'body' => 'required',
]);
$entry = new Comment();
$entry->body = $request->body;
$entry->save();
return redirect('/');
}
I need to also pass in the films table id, known in the comments table as film_id. This field can not be null. The above doesnt take this field into account and so I get the following message:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL
constraint failed: comments.film_id (SQL: insert into "comments"
("body", "updated_at", "created_at") values
I have tried to pass in the film id by doing variations of the below but no success.
public function addComment(Request $request, $id)
{
$request->validate([
'body' => 'required',
'film_id' => 'required',
]);
$entry = new Comment();
$film_id = Film::find($id);
$entry->body = $request->body;
$entry->film_id = $film_id;
$entry->save();
return redirect('/');
Comment model:
class Comment extends Model
{
public function film()
{
return $this->belongsTo(Film::class);
}
}
Film model:
class Film extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
you are not passing the id, you were passing the film object
public function addComment(Request $request, $id)
{
$film = Film::find($id);
$entry = new Comment();
$entry->body = $request->body;
$entry->film_id = $film->id;
$entry->save(); //your comment is saved with proper film_id
}
or
public function addComment(Request $request, $id)
{
$film = Film::find($id);
$film->comments()->save(['body'=>$request->body]);
}
In the form when I echo the session value it is prompted no errors, but when I try to save it on the database in the model the value is not saved.
Here is my view:
(I just posted here what I think is needed.)
<?php
$userid = Yii::app()->session['iduser'];
echo $userid;
?>
Here is my controller:
The contentid, title and content are saved in the database only the userid is my problem. In my database I set the userid as int(11) not null
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
$this->redirect(array('content','title'=>$model->title));
$this->redirect(array('content','content'=>$model->content));
$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}
And here is my model:
<?php
class ContentForm extends CActiveRecord{
public $content;
public $title;
public $userid;
public function tableName(){
return 'tbl_content';
}
public function attributeLabels(){
return array(
'contentid' => 'contentid',
'content' => 'content',
'title' => 'title',
'userid' => 'userid',
);
}
public function rules(){
return array(
array('content, title, userid', 'safe'),
);
}
}
Your user id Stored in Session it can accessed anywhere in the MVC
Try this on your controller
public function actionContent(){
$model=new ContentForm;
if(isset($_POST['ContentForm'])) {
$model->attributes=$_POST['ContentForm'];//The post values
$model->userid=Yii::app()->session['iduser'];
if($model->save())
$this->redirect(array('content','contentid'=>$model->contentid));
//$this->redirect(array('content','title'=>$model->title));
//$this->redirect(array('content','content'=>$model->content)); //Why this to many redirects here the first redirect only works here
//$this->redirect(array('content','userid'=>$model->userid));
}
$this->render('content',array('model'=>$model));
}