i need an explanation about how this update code works (Laravel) - laravel

public function editCategory(Request $request,$id = null){//we pass the $id
if($request->isMethod('post')){
$data = $request->all();
Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
'description'=>$data['description'],'url'=>$data['url']]);
return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully');
}
$categoryDetails = Category::where(['id'=>$id])->first(); return view('admin.categories.edit_category')->with(compact('categoryDetails'));
}
//this code is working in my controller

Simply there are two ways to invoke this action:
Request in HTTP POST method
if you make a request to the URL /admin/edit-category/12345 in HTTP POST method
then you make an update of the model called Category with id = $id (in my example
$id is 12345) and then you will be redirected in /admin/view-categories with a flash
message variable valorized with Category Updated Successfully
Request in HTTP GET method (or any other HTTP method)
if you make a request to the URL /admin/edit-category/12345 in HTTP GET method then the action responds with a view of the model Category with id = $id (in my example $id is 12345) and put the fields of the model in the view params.

ok i will explain to you this is edit fonction so it make modification of data stored in database
if($request->isMethod('post')){//if your data submitted to database
$data = $request->all();//recupration of all information
Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
'description'=>$data['description'],'url'=>$data['url']]);//change description , categoryname and url
return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully')//and return seccess alert in your view;
}
$categoryDetails = Category::where(['id'=>$id])->first(); return view('admin.categories.edit_category')->with(compact('categoryDetails'));

public function editCategory(Request $request,$id = null){//we pass the $id
//check that the request is a POST request
if($request->isMethod('post')){
//Okay so it is, now store all request parameter in it's own variable
$data = $request->all();
//Access the Eloquent model Category, checks the id and updates
//accordingly
Category::where(['id'=>$id])->update(['name'=>$data['category_name'],
'description'=>$data['description'],'url'=>$data['url']]);
//Return redirect to view-categories with a success message
return redirect('/admin/view-categories')->with('flash_message_success','Category Updated Successfully');
}
//check the first id and return the view with the details, this would only be hit if the above if statement wasn't (wasn't a POST request for example)
$categoryDetails = Category::where(['id'=>$id])->first(); return view('admin.categories.edit_category')->with(compact('categoryDetails'));

Related

Route model binding with relationship in laravel

PUT|PATCH api/v1/tweets/{tweet}/comments/{comment} tweets.comments.update › Api\\V1\\TweetCommentController#update
i've this above route, and i'm trying to bind the relationship from controller
I'm passing formadata with key comment = This is a test comment
I tried this code below in TweetCommentController.
public function update(Tweet $tweet, TweetComment $comment, TweetCommentRequest $request)
but this is not working. it just redirect to the login page.
I also tried this below too
public function update(Tweet $tweet, TweetComment $comment)
This one seems working, atleast i'm able to log $tweet and $comment., but i cannot access the form data.
Please help.
My mistake,
I tried the api call from postman, and i used method PUT.
I changed the method to POST and add a new key _method = PUT in form data
so, my current (working) code looks like this
API call
POST {{base_url}}/tweets/1/comments/2
form-data :
comment = "edited test comment"
_method = PUT
Controller
public function update(TweetCommentRequest $request, Tweet $tweet, TweetComment $comment){
$comment->update($request->validated());
return $this->sendResponse([
'message' => __('Comment updated successfully.'),
'comment' => $comment
]);
}

How to return one controller method from another?

I have a method that response to ajax call and return a view to ajax with a big query, and of course this method have (Request $request).
So in the another method I want to return view of above method with it's data, how to return above method when it give some request data?
please note that when the request->query is empty, the method return all data with query='' and it is correct.
public function item_search(Request $request){
if($request->ajax()){
$result = MyModel::where('id' , $request->query)->get();
return view('admin.ajax.searchResult')->with(['result' => $result ]);
}
}
public function second_method(){
// there is not any $request
// how to set $request->query = '';
return $this->item_search($request);
}
my second_method() not give any request, it run by another route,
now the second_method() called. how to call item_search() method from that ?

Is it necessary to protect destroy method in Laravel from an authenticated user that did not create a post

I have the following middleware in my PostController.
public function __construct()
{
$this->middleware('auth')->except(['index', 'show']);
}
I understand any authenticated user can still edit a post by visiting localhost/posts/{post}/edit so I've protected that by the following code.
public function edit(Post $post)
{
if(auth()->user()->id === $post->user_id){
$categories = Category::all();
return view('edit-post', compact(['post', 'categories']));
} else{
abort(403, 'Unauthorized.');
}
}
Now, I'm wondering is it necessary to protect the destroy method? Is it possible for an authenticated user to delete a post they didn't create in this case? If they can could I kindly know how they can?
My destroy method
public function destroy(Post $post)
{
Storage::disk('public')->delete($post->imagePath);
$post->delete();
return redirect(route('posts.index'))->with('flash', 'Post Deleted Successfully');
}
one easy way to protect all your methods that need authentification is to use relations.
You are sending a post id in the URL by use model injection to preload $post from DB. Avoid that and use the id of the post yourself
public function destroy($postId)
{
$post = auth()->user()->posts()->findOrFail($postId);
Storage::disk('public')->delete($post->imagePath);
$post->delete();
return redirect(route('posts.index'))->with('flash', 'Post Deleted Successfully');
}
The route will return a 404 if the post id is not one of the user owned posts.
Same for the edit
public function edit($postId)
{
$post = auth()->user()->posts()->findOrFail($postId);
$categories = Category::all();
return view('edit-post', compact(['post', 'categories']));
}
As for the change in response code 404 instead of a 403, it is on purpose, since the user is authenticated and you dont want any user to know if another post with random ID that is not his exists or not hence 404. like if he put a non existing post id to delete or edit.
First, you should be read about Laravel policy, which will make your code more clear.
For destroy method,
I will give you an example, you can try it BTW
post_table
id
user_id
title
1
40
Post1
2
50
Post2
If the user id: 40 tries to delete the post witch id is id: 1 there is no problem,
BUT let's say the user knows about the web app and just changes the id in the URL localhost/posts/2/delete, He/She will delete any post without policy.

Laravel 8 routing

I have a a function which gets all the data from the date inputted by the user and pass it to the table in view. In that table individual row of data retrieved from database has one anchor tag which carries id of each row in database to update the column in the database. All works fine but i'm having problem in redirecting to the table after update. i'm getting problem due redirecting to the page maturity_reqController/'whatever_ids' which doesnot exists but dont khow how to fix it.
My anchor Tag goes
Request
My Route goes
Route::get('maturity_reqController/{id}', [SettlementController::class,'maturity_reqController']);
my Controller goes
function maturity_reqController($id){
$forset = new Settlement();
$forset->org_document_id = $id;
$forset->save();
$data = Doc::find($id);
$data->status = "Maturity Requested";
$data->save();
return redirect('maturity_reqController');
}
You can try this
return redirect()->back();
for more details : laravel redirects
Add a name to your route like so:
Route::get(
'maturity_reqController/{id}',
[SettlementController::class,'maturity_reqController']
)->name('maturity.req');
Then whenever you need to link to that route use
Request
Edit: to redirect to that route:
return redirect()->route('maturity.req', ['id' => $items->id]);
More on Named Routes
Your Link
Request
web.php
Route::get('maturity_reqController/{id}', [SettlementController::class,'maturity_reqController'])->name('maturity_req');
Controller
function maturity_reqController($id) {
$forset = new Settlement();
$forset->org_document_id = $id;
$forset->save();
$data = Doc::find($id);
$data->status = "Maturity Requested";
$data->save();
return redirect()->route('maturity_req', ['id' => 'Your ID'])->with('success', 'Your Message');
}

How to use parameter from function to create an URL? Laravel Routing

I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}

Resources