FatalThrowableError (E_ERROR) Call to a member function replies() on null - php

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

Related

Argument 3 passed to App\Events\NoticeAnnouncement::__construct() must be an instance of App\User

I am trying to send mail to all students when a notice will be posted by a teacher. For this, I am calling a event when the notice is being created, and passed notice,teacher and user through the event variable. But its giving a error saying that "Argument 3 passed to App\Events\NoticeAnnouncement::__construct() must be an instance of App\User, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\iiucsmartclassroom\app\Http\Controllers\Teacher\NoticeController.php".
Here is my Notice Controller :
public function submitNotice(Request $request){
$validatedData = $request->validate([
'notice_title' => 'required|max:255',
'notice_description' => 'required|max:3000',
'notice_file.*' => 'mimes:jpg,jpeg,pdf',
]);
$data=array();
$data['teacher_id']=$request->teacher_id;
$data['notice_title']=$request->notice_title;
$data['notice_description']=$request->notice_description;
$data['notice_post_date']=$request->notice_post_date;
$data['notice_post_time']=$request->notice_post_time;
$image=$request->file('notice_file');
if ($image) {
$image_name= str::random(5);
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$upload_path='notices/';
$image_url=$upload_path.$image_full_name;
$success=$image->move($upload_path,$image_full_name);
if ($success) {
$data['notice_file']=$image_url;
$notices = DB::table('notices')
->insertGetId($data);
$notice = Notice::find($notices);
$teacher = Teacher::find($notice->teacher_id);
$users = User::all();
event(new NoticeAnnouncement($notice,$teacher,$users));
if ($notices) {
$notification=array(
'message'=>'Notice Posted Successfully',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}else{
$notification=array(
'message'=>'Could not be able to post the Notice',
'alert-type'=>'error'
);
return Redirect()->back()->with($notification);
}
}else{
return Redirect()->back();
}
}else{
$notice = DB::table('notices')
->insert($data);
if ($notice) {
$notification=array(
'message'=>'Notice Posted Successfully',
'alert-type'=>'success'
);
return Redirect()->back()->with($notification);
}else{
$notification=array(
'message'=>'Could not be able to post the Notice',
'alert-type'=>'error'
);
return Redirect()->back()->with($notification);
}
}
}
Here is my Event :
public $notice,$teacher,$user;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Notice $notice,Teacher $teacher,User $user)
{
$this->notice = $notice;
$this->teacher = $teacher;
$this->user = $user;
}
Here is my Listener :
public function handle(NoticeAnnouncement $event)
{
foreach ($event->user as $user) {
Mail::to($user->email)->send(new SendNotice($event->notice,$event->teacher,$event->user));
}
}
You send a collection of users to the method instead of the user model:
Mail::to($user->email)->send(new SendNotice($event->notice,$event->teacher,$user));
You use find($key) function to get Illuminate\Database\Eloquent\Model from \Illuminate\Database\Eloquent\Collection.
public function handle(NoticeAnnouncement $event)
{
foreach ($event->users as $key => $user) {
Mail::to($user->email)->send(new SendNotice($event->notice,$event->teacher,$event->users->find($key)));
}
}

Call to a Member Function fill() on Null Laravel

I've been trying to edit a record. My code will create a new record if the data is null. However, I get the following error:
Call to a member function fill() on null.
I'm not sure what I did wrong; maybe I didn't declare?
Controller
<?php
public function auctionUpdate(Request $request, MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
DB::transaction(function() use ($request, $mediaSite, $auction){
$auction->fill($request->only([
'status', 'start_time', 'end_time', 'period_start_date'
]));
if($auction == null)
$auction = new Auction();
$auction->save();
});
return view('admin.media-site.show', [
'mediaSite' => $mediaSite,
'auction' => $auction
]);
}
You should check if auction is null before fill()
your modified script
public function auctionUpdate(Request $request, MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
DB::transaction(function() use ($request, $mediaSite, $auction){
if($auction == null)
$auction = new Auction();
$auction->fill($request->only([
'status', 'start_time', 'end_time', 'period_start_date'
]));
$auction->save();
});
return view('admin.media-site.show', [
'mediaSite' => $mediaSite,
'auction' => $auction
]);
}

Adding ID to function to prevent not null error

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

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::update() must be of the type array, object given

I want to update a data in the database
i have controller
public function update(Identity $identity, Request $request)
{
$data = new Identity();
$data->date = $request['date'];
$data->code = $request['code'];
$data->name = $request['name'];
$request->user()->identity()->update($data);
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
Model Identity
public function user()
{
// Each data is owned by only one user
return $this->belongsTo('App\User');
}
Model User
public function identity()
{
// Each user will have a lot of data
return $this->hasMany('App\Identity');
}
And i found an error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::update() must be of the type array, object given.
You already have the Identity model with the route model binding. You can do one of the below.
public function update(Identity $identity, Request $request)
{
$identity->date = $request['date'];
$identity->code = $request['code'];
$identity->name = $request['name'];
$identity->save();
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
Or (Make sure you set the $fillable property in the model for this to work)
public function update(Identity $identity, Request $request)
{
$identity->update([
'date' => $request['date'],
'code' => $request['code'],
'name' => $request['name'],
]);
Session::flash('flash_message', 'Update success.');
return redirect('identity.index');
}
This line
$data = new Identity();
creates an object. Below that you are setting its properties. Instead, it looks like you can pass your properties directly into the function:
public function update(Identity $identity, Request $request)
{
$request->user()->identity()->update(array($request));
...
}
Of course you might also want to restrict your request to just what's needed:
public function update(Identity $identity, Request $request)
{
$params = array_intersect_key(array($request), array_flip(['date', 'code', 'name']))
$request->user()->identity()->update($params);
...
}

Column not found in SQL laravel 5.4

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
}
}
?>

Categories