i am creating a comment system with reply, but i have problem with reply store.
it does not working and display any error!
i do not know what to do!?
i have polymorphic relation
comment controller
public function store(Request $request,Post $post)
{
$this->validate($request,[
'website' => 'nullable|active_url',
'comment' => 'required|min:5'
]);
$comment = new Comment();
$comment->user_id = Auth::user()->id;
$comment->name = Auth::user()->fname;
$comment->email = Auth::user()->email;
$comment->website = $request->website;
$comment->body = $request->comment;
$post->comments()->save($comment);
Session::flash('success', 'Comment Send Successfully');
return back();
}
public function reply(Request $request,Comment $comment)
{
$this->validate($request,[
'website' => 'nullable|active_url',
'commentReply' => 'required|min:5'
]);
$reply = new Comment();
$reply->user_id = Auth::user()->id;
$reply->name = Auth::user()->fname;
$reply->email = Auth::user()->email;
$reply->website = $request->website;
$reply->body = $request->replyComment;
$comment->comments()->save($reply);
Session::flash('success', 'Comment Replyed Successfully');
return back();
}
comment model
protected $fillable = [
'parent_id', 'user_id', 'post_id', 'name', 'email', 'website', 'body', 'approved'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
public function commentable()
{
return $this->morphTo();
}
public function comments()
{
return $this->morphMany(Comment::class,'commentable');
}
and these are my routes
/* comment */
Route::post('/post/{post}/comment','CommentController#store')->name('comment.store');
Route::post('/comment/reply/{comment}','CommentController#reply')->name('comment.reply');
i do not have problem with comment storing, problem is reply does not store.
this is problem! :)
Related
I have users table with hasMany educational backgrounds & educational awards. Then that educational backgrounds hasMany educational awards
Here's my Testcase when user uploads image my endpoint receives it
public function testuploadUsersImageEducationalAwards()
{
Storage::fake('public');
$photo = UploadedFile::fake()->create('photo.png')->size(25000);
$data = [
'photo' => $photo,
'award' => $this->faker->word,
'educational_background_id' => EducationalBackground::factory()->create()->id
];
$this->withoutExceptionHandling();
$response = $this->sendPostRequestToEndpoint($data, 200);
$data['file_name'] = $response['file_name'];
unset($data['photo']);
$response->assertJson($data)
->assertJsonStructure([
'id',
'award',
'photo',
'educational_background_id',
'created_at',
'updated_at',
]);
$this->assertDatabaseHas('users.educational_awards', $data);
}
Here's my endpoint with assert status 200
private function sendPostRequestToEndpoint(array $data, $status)
{
return $this->json("POST", '/api/users/educational-award/upload-picture', $data)->assertStatus($status);
}
UPDATE
Here's my EducationalBackgroundFactory
class EducationalBackgroundFactory extends Factory
{
protected $model = EducationalBackground::class;
public function definition()
{
return [
'user_id' => User::factory()->create()->id,
'studies_type' => $this->faker->randomElement([EducationalBackground::BASIC, EducationalBackground::SECONDARY, EducationalBackground::UNDERGRADUATE, EducationalBackground::GRADUATESCHOOL]),
'year' => Carbon::now()->format("Y"),
'course' => $this->faker->word,
];
}
}
Here's my EducationalBackground model
class EducationalBackground extends Model
{
use HasFactory;
const BASIC = "basic";
const SECONDARY = "secondary";
const UNDERGRADUATE = "undergrad";
const GRADUATESCHOOL = "grad";
protected $table = 'users.educational_backgrounds';
protected $fillable = [
'user_id',
'studies_type',
'year',
'course',
];
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function educationalAwards()
{
return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id");
}
}
Here's my migration
public function up()
{
Schema::create('users.educational_backgrounds', function(Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->enum('studies_type', ['basic', 'secondary', 'undergrad', 'grad']);
$table->integer('year');
$table->string('course')->nullable();
$table->timestamps();
});
}
Here's my controller code
public function uploadUsersImageEducationalAwards(UserImageRequest $request, EducationalBackground $educational_background)
{
$uploaded_image = $request->photo->store('users/educational_awards');
$file_type = $request->photo->getClientOriginalExtension();
$file = EducationalAward::create([
'educational_background_id' => $educational_background->id,
'award' => $request->award,
'photo' => $uploaded_image,
]);
return response()->json($file, 200);
}
But this gives me 500 status which i found a way to log error in details. Here's an image for more clarity
remove unset function before sending response.
I have a relationship between post and tag in post show page I'm trying to display post related to the post show content but excluding the main show content it's not working and I'm not getting error.
class PostShow extends Component
{
public $post;
public $body;
public $slug;
public $comment;
public function mount(Post $post) {
$this->post = $post;
}
protected $rules = [
'comment' => 'string|required|min:3|max:5000',
];
protected $listeners = [
'commentWasAdded'
];
public function commentWasAdded() {
$this->post->refresh();
}
public function render() {
$post = Post::where('slug', '=', $slug)->first();
$related = Post::whereHas('tags', function ($q) use ($post) {
return $q->whereIn('name', $post->tags->pluck('name'));
})
->where('id', '!=', $post->id) // So you won't fetch same post
->get();
return view('livewire.post-show',[
'related' => $related,
]);
}
}
I'm working on a questionnaire project and I ran into an error saying:
Undefined index: exams
This happened when I was trying to store responses to my database.
Here is my controller code:
public function store(Math $math)
{
$data = request()->validate([
'responses.*.answer_id' => 'required',
'responses.*.question_id' => 'required'
]);
$exam = $math->exams()->create($data['exams']);
$exam->examanswers()->createMany($data['examanswers']);
return 'Thank You';
}
Here is my exam model:
{
use HasFactory;
protected $fillable = ['exam'];
public function math()
{
return $this->belongsTo(Math::class);
}
public function examanswers()
{
return $this->hasMany(ExamAnswer::class);
}
}
question model:
{
use HasFactory;
protected $fillable = ['question'];
public function math()
{
return $this->belongsTo(Math::class);
}
public function answers()
{
return $this->hasMany(Answer::class);
}
}
Math model:
{
use HasFactory;
protected $fillable = [
'user_id', 'title', 'purpose', 'exam'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function questions()
{
return $this->hasMany(Question::class);
}
public function exams()
{
return $this->hasMany(Exam::class);
}
}
Please help me look into it.
request()->validate(RULES) will return an array with all the existing rules' indexes. It will not return all data present, just what it is in the rules and present.
Read how $request->validate() works.
For example:
If you send home = 'Address', name = 'John' and email = 123, but your rules are:
$data = $request->validate([
'home' => 'required',
'name' => 'required',
]);
Then, if you want to use $data you would have (dd($data)):
$data['home']: Address
$data['name']: John
But email = 123 would not be present in $data.
I'm new to Laravel. My data doesn't seem to get to the database. Here's my Controller code:
public function store(Request $request)
{
$rules = [
'first_name' => 'required|string|min:3|max:255',
'last_name' => 'required|string|min:3|max:255',
'gender' => 'required|string|min:3|max:255',
'qualifications' => 'required|string|min:3|max:255'
];
$validator = FacadesValidator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect('/home')
->withInput()
->withErrors($validator);
} else{
$data = $request->input();
try {
$crud = new CRUD;
$crud->first_name = $request->get('first_name');
$crud->last_name = $request->get('last_name');
$crud->gender = $request->get('gender');
$crud->qualifications = $request->get('qualifications');
$crud->save();
return redirect('/home')->with('status',"Insert successfully");
} catch (\Throwable $th) {
return redirect('/home')->with('failed',"Insert Failed");
}
}
}
And my Model:
protected $table = '$user';
protected $fillable = [
'first_name', 'last_name', 'gender', 'qualifications'
];
public $timestamps = true;
And my route(Web.php):
Route::post('/store', [App\Http\Controllers\CRUDController::class, 'store'])->name('insert');
Here is my migration for the users table:
Schema::create('user', function(Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('gender');
$table->string('qualifications');
$table->timestamps();
});
You should fix your table name in your model, since your table is called user:
protected $table = "user";
Also, you can use mass assignment to fill your models:
$crud = CRUD::create($request->validated());
It should fix your problem.
I want to insert a Post record with multiple tags so here's my code in Post#store:
$post = Post::create(array(
'title' => $request->title,
'body' => $request->body,
'user_id' => Auth::id(),
));
if($post && $request->tags)
{
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach($tagNames as $tagName)
{
$tag = Tag::firstOrCreate(['name'=>$tagName]);
if($tag)
{
$tagIds[] = $tag->id;
}
}
$post->tags()->attach($tagIds);
}
but it give me an errors "Call to a member function attach() on null". when i'm checked in mysql the tags is already in there but i can't find any entry on my post_tag tables. here's my post model:
class Post extends Model
{
protected $fillable = ['user_id','title','slug','body','tags','category_id','featured'];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
$this->hasMany('App\Tag');
}
}
You need to return the call the hasMany in your Post model.
public function tags()
{
return $this->hasMany('App\Tag');
}
Update
You should use belongsToMany not hasMany.