Update data in laravel 6 - laravel

I try to create crud in laravel 6. Create, Read and Delete process is running well. But when Update process, the data in table not change. Could anyone help me to find the problem ? The following my code.
Route
Route::get('/blog', 'BlogController#index');
Route::get('/blog/add','BlogController#add');
Route::post('/blog/store','BlogController#store');
Route::get('/blog/edit/{id}','BlogController#edit');
Route::post('/blog/update','BlogController#update');
Controller
public function index()
{
$blog = DB::table('blog')->get();
return view('blog',['blog' => $blog]);
}
public function edit($id)
{
$blog = DB::table('blog')->where('blog_id', $id)->get();
return view('edit', ['blog'=>$blog]);
}
public function update(Request $request)
{
DB::table('blog')->where('blog_id',$request->blog_id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
View
#foreach ($blog as $n)
<form method="post" action="/blog/update" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach

You must provide id in your route
Route::post('/blog/update/{id}','BlogController#update');
In update method add parameter id and then find product against id
public function update(Request $request, $id)
{
DB::table('blog')->where('blog_id',$id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
#foreach ($blog as $n)
<form method="post" action="{{ route('your route name'), ['id' => $$n->id] }}" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach

try separating the update into two statements like so
$blog = DB::table('blog')->where('blog_id',$id)->first();
$blog->update([
'blog_title' => $request->title,
'author' => $request->author]);
Also you might want to use models in the future so you can do it like
$blog = Blog::where('blog_id',$id)->first();
Doesn't really shorten your code but it improves the readibility.

Do your update like this:
public function update(Request $request)
{
$post = DB::table('blog')->where('blog_id',$request->blog_id)->first();
$post->blog_title = $request->title;
$post->author = $request->author;
$post->update();
return redirect('/blog');
}

Related

Laravel 9 how to pass parameter in url from one controller to another controller?

I was facing this problem of missing parameter when trying to pass a parameter from one controller to another controller. The parameter is $id whereby the data is originally from post method in details blade.php into function postCreateStepOne However, I want to pass the data into a new view and I return
redirect()->route('details.tenant.step.two')->with( ['id' => $id]
);}
And this is where error occur. However, it works fine if I skip it into a new route and directly return into a view with the compact parameter. For Example,
return view('document.details-step-two', compact('id', 'property'));
However, I would prefer a new url as I was doing multistep form using Laravel.
Error
web.php
Route::get('/document/details/viewing/{id}', 'ViewDetails')->name('details.tenant');
Route::post('/document/details/viewing/{id}', 'postCreateStepOne')->name('post.step-one');
Route::get('/document/details/viewing/step-2/{id}', 'ViewDetailsStep2')->name('details.tenant.step.two');
TenanatController.php
public function viewDetails($id){
$view = Properties::findOrFail($id);
return view('document.details', compact('view'));
}
public function ViewDetailsStep2(Request $request, $id){
$view = Properties::findOrFail($id);
$property = $request->session()->get('property');
return view('document.details-step-two', compact('view', 'property'));
}
public function postCreateStepOne($id, Request $request)
{
$validatedData = $request->validate([
'property-name' => 'required',
]);
if(empty($request->session()->get('property'))){
$property = new Tenancy();
$property->fill($validatedData);
$request->session()->put('property', $property);
}else{
$property = $request->session()->get('property');
$property->fill($validatedData);
$request->session()->put('property', $property);
}
return redirect()->route('details.tenant.step.two')->with( ['id' => $id] );
}
details.blade.php
<form action="{{ route('post.step-one', $view->id) }}" method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="title">Property Name:</label>
<input type="text" value="" class="form-control" id="property-name" name="property-name">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</form>
When you use with on a redirect the parameter is passed through the session. If you want to redirect to a route with a given route parameter you should pass that parameter in the route function itself like e.g.
return redirect()->route('details.tenant.step.two', ['id' => $id]);

Refresh same livewire component after form wire:submit.prevent

Please I'd like to refresh same component after form submit. There is an if statement that allows the the form to display in the component. I'd like to refresh the whole component so as not to show the form again after submit.
I already tried emit but I don't think it works for same component.
Livewire component
<?php
namespace App\Http\Livewire;
use App\Lesson;
use App\Question;
use App\QuestionsOption;
use App\TestsResult;
use Livewire\Component;
class LessonTest extends Component
{
public $test_result;
public $lesson;
public $test_exists;
public array $question = [];
//protected $listeners = ['testDone' => 'render'];
public function mount($test_exists, $lesson, $test_result)
{
$this->lesson = $lesson;
$this->test_exists = $test_exists;
$this->test_result = $test_result;
}
public function lessonTest()
{
$lesson = Lesson::where('slug', $this->lesson->slug)->firstOrFail();
$answers = [];
$test_score = 0;
foreach ($this->question as $question_id => $answer_id) {
$question = Question::find($question_id);
$correct = QuestionsOption::where('question_id', $question_id)
->where('id', $answer_id)
->where('correct', 1)->count() > 0;
$answers[] = [
'question_id' => $question_id,
'option_id' => $answer_id,
'correct' => $correct,
];
if ($correct) {
$test_score += $question->score;
}
/*
* Save the answer
* Check if it is correct and then add points
* Save all test result and show the points
*/
}
$test_result = TestsResult::create([
'test_id' => $this->lesson->test->id,
'user_id' => \Auth::id(),
'test_result' => $test_score,
]);
$test_result->answers()->createMany($answers);
$this->reset(['question']);
$this->emit('testDone');
}
public function render()
{
return view('livewire.lesson-test');
}
}
Livewire Blade View
<div>
#if ($test_exists)
<hr />
<h3>Test: {{ $lesson->test->title }}</h3>
#if (!is_null($test_result))
<div class="alert alert-info">Your test score: {{ $test_result->test_result }} /
{{ $lesson->test->questions->count() }}</div>
#else
<form wire:submit.prevent='lessonTest' action="{{ route('lessons.test', [$lesson->slug]) }}"
method="post">
{{ csrf_field() }}
#foreach ($lesson->test->questions as $question)
<b>{{ $loop->iteration }}. {{ $question->question }}</b>
<br />
#foreach ($question->options as $option)
<input type="radio" wire:model='question.{{ $question->id }}'
name="questions[{{ $question->id }}]" value="{{ $option->id }}" />
{{ $option->option_text }}<br />
#endforeach
<br />
#endforeach
<button class="btn btn-success btn-lg refresh" type="submit">Submit</button>
</form>
#endif
<hr />
#endif
</div>
Thank You. I got it solved, I forget that I passed the test result from the controller before, so I had to recall the test_result and also the test_exist inside the lessonTest action.
$this->test_result = TestsResult::where('test_id', $this->lesson->test->id)
->where('user_id', \Auth::id())
->first();
$this->test_exists = true;

Update Comment in Laravel

I am new at Laravel and I want to use if statement inside Laravel Controller.
So I have a form tag where I can add comments. I want to edit comments in the same form.
Here is my form tag:
<form method="post" action="/hotels/{{$id}}" name="review_hotel">
#csrf
<div class="form-group">
<textarea name="comment" id="comment" class="form-control" style="height:100px"
placeholder="Write your review"></textarea>
#error('comment')
<p class="text-danger">{{$message}}</p>
#enderror
</div>
<input type="submit" value="Submit" class="btn_1" id="submit-review">
</form>
I have a script, with the help of this script I can add a comment that I want to change to the textarea.
After this I have no idea how to update it in my controller.
This is CommentController:
public function comment(CommentRequest $request, $id)
{
$comment = new Comment();
$comment->object_id = $id;
$comment->user_id = Auth::id();
$comment->comment = $request['comment'];
$comment->save();
return redirect('/hotels/'.$id);
}
I think I need to write "if" statement in my controller, but I don't know how.
maybe there is a simpler way to update comment?
On your model Comment.php mark form variables as fillable
public $fillable = ['object_id', 'user_id', 'comment'];
then use this Model function (Eloquent)
Comment::updateOrCreate(
[
'object_id' => ...,
'user_id' => ...,
],
[
'object_id' => ...,
'user_id' => ...,
'comment' => ...,
]
);
https://laravel.com/docs/5.8/eloquent#other-creation-methods

Laravel multiple delete checkbox?

I want to delete only checked tasks. At the moment I have this:
<form method="POST" action="/destroy">
#foreach($tasks as $t)
<label>
<input type="checkbox" name="checked[]" value="$t->id">
</label>
#endforeach
<button type="submit">Submit!</button>
</form>
This is my Controller
public function destroy(Request $request)
{
$this->validate($request, [
'checked' => 'required',
]);
$checked = $request->input('checked');
Task::destroy($checked);
}
And this is my route
Route::post('/destroy', [
'uses' => 'Controller#destroy',
]);
I don't get no error but the system does not work
I fixed the problem! Thanks for your support!
The problem was that my id variable was a hash.

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

Resources