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]);
}
Related
i have the controller php
public function storecontact(Request $request)
{
$img_name=time() .'.' . $request->url->getClientOriginalExtension();
$this->validate($request,[
'content' => 'unique:emails,content,subject'
]);
$request->user()->id;
$email= new Email;
$email->name=request('name');
$email->user_id = auth()->user()->id;
// $email->subject_id = subject()->id;
$email->email=request('email');
$email->subject=request('subject');
$email->hood=request('hood');
$email->street=request('street');
$email->content=request('content');
$email->priority=request('priority');
$email->url=$img_name;
$email->status=("ממתין לטיפול");
$email->subject_id= $subject->id;
//$email->subject_id= request($id);
//$email->subject_id=request($id);
$email->save();
$request->url->move(public_path('photos'),$img_name);
return redirect()->back();
}
this is the subject model realationship
public function emails()
{
return $this->hasMany(Email::class);
}
and the email model realationship
public function subject()
{
return $this->belongsTo(Subject::class);
}
is there any way to insert the subject_id to the emails table?
Error :
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `posts` (`title`, `body`, `updated_at`, `created_at`) values (fdsfsd, dfds, 2020-06-09 16:32:53, 2020-06-09 16:32:53))
This is the PostsController
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required',
'body'=>'required'
]);
$post = new Post ;
$post->title = $request->input('title');
$post->body= $request->input('body');
$post->save();
return redirect('/posts')->with('success','Post created');
}
and this is the migration i've done
public function up()
{
Schema::table('posts',function($table){
$table->String('user_name');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('posts',function($table){
$table->dropColumn('user_name');
});
}
}
when I type this : php artisan migrate:rollback , the store fucntion work perfectly , but the post doesn't have the name of user that created it
and thanks for advance .
you have many weak points in your code ....
the column 'user_name' its place is 'users' table not 'posts' table, so your migration should not take place ....
you must set 'user_id' in store method and in $fillable in Post model like:
class Post extends Model
{
$protected $fillable=['title','body','user_id'];
public function user()
{
return $this->belongsTo(User::class,'user_id');
}
}
then .. in your controller you must get 'user_id' from the current logged in user:
public function store(Request $request)
{
$this->validate($request,[
'title'=>'required',
'body'=>'required'
]);
$post = new Post() ;
$post->title = $request->input('title');
$post->body= $request->input('body');
$post->user_id=$request->user()->id;
$post->save();
return redirect('/posts')->with('success','Post created');
}
you must be sure of that the route that is bound to this controller method should have auth middleware ...
now: if you want to get post with user name:
$postWithUserName=Post::where('id',$post_id)->with('user:id,name')->get();
make sure you have a column 'name' in users table ...
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'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
}
}
?>
This is my Items model . Now i want to add a new item but i get this error: SQLSTATE[23000]: Integrity constraint violation: 1048
<?php
class Items extends Eloquent
{
protected $guarded = [
'id',
];
protected $fillable = [
'name',
'description',
'price',
'brand',
];
protected $table = 'items';
public function user()
{
return $this->hasOne('User', 'user_ID', 'id');
}
public function size()
{
return DB::table('sizes')->select('size')
->where('id', $this->size_ID)->first()->size;
}
public function color()
{
return DB::table('colors')->select('color')
->where('id', $this->color_ID)->first()->color;
}
public function condition()
{
return DB::table('conditions')->select('type')
->where('id', $this->condition_ID)->first()->type;
}
public function category()
{
return DB::table('categories')->select('category')
->where('id', $this->category_ID)->first()->category;
}
public function images()
{
return DB::table('images')->select('image')
->where('item_id', $this->id)->first()->image;
}
}
And this is my post method to save item.
public function store()
{
$item = new Items;
$item->user_ID = Auth::id();
$item->name = Input::get('name');
$item->description = Input::get('description');
$item->price = Input::get('price');
$item->brand = Input::get('brand');
$item->category = Input::get('Category');
$item->condition = Input::get('Condition');
$item->color = Input::get('Color');
$item->save();
}
Here is a picture of category table , condition and color table has the same logic.
http://imgur.com/9NCMYui
You are creating a relationship between User and Item while not using it.
You can set the populate the relationship manually by filling in the id yourself, but then you don't use the power of the Eloquent ORM.
What I would suggest is getting the current user.
And saving it like this.
$item->user()->save($user);
I suggest for the name of the class Item and not Items.
I find it having much more logic and so do most of the programmers.
The table can still be called items.