The value does not change in the database - php

I made a button to update a user's access to the website and I get an error. I searched here but I did not find the answer to help me, can you give me some advice?
This is the error: Creating default object from empty value
Controller:
public function suspendUser(Request $request, $id) {
$user = User::find($id);
$user->userAcces = 0;
$user->save();
return back();
}
View::
<div class="col-md-3 col-sm-3">
<form>
<i class="fa fa-eye" aria-hidden="true"></i>
<i class="fa fa-ban" aria-hidden="true"></i>
<i class="fas fa-trash"></i>
<i class="fas fa-user-friends"></i>
<form>
</div>
Route:
Route::get('/updateUser/{id}', 'UserController#suspendUser');
I tried other things but failed, maybe something went wrong in the controller?

It means this user is not found with this $id and $user is null , so check the $id which sent to the suspendUser method, and it's better to use User::findOrFail($id); in order to return 404 if model not found ,and not face these kinds of errors.

Related

Too few arguments to function App\Http\Controllers\ProduitController::show()

I wants to show users list into my dashboard pannel but it shows me this problem :
Too few arguments to function App\Http\Controllers\ProduitController::show(), 0 passed in C:\wamp64\www\Ecommerce\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected
Controller File :
public function show($id)
{
$produit = Produit::find($id);
return view('produits', compact('produit'));
}
blade file :
#foreach($produits as $produit)
<div class="product__item__pic set-bg" data-setbg="{{ asset('img/uploads/'.$produit->image)}}">
<ul class="product__item__pic__hover">
<li><i class="fa fa-heart"></i></li>
<li><i class="fa fa-retweet"></i></li>
<li><i class="fa fa-shopping-cart"></i></li>
</ul>
</div>
<div class="product__item__text">
<h6>{{ $produit->designation }}</h6>
<h5>{{ $produit->prix_uni }} Mad</h5>
</div>
#endforeach
Route :
Route::get('/produits','ProduitController#show');
If you have an id in your function definition, this should also be there in route definition. Route variables is defined with {id}.
Route::get('/produits/{id}','ProduitController#show');
For a best practice, use model binding, if you call your route variable the same as the model, you can automatically load it by typehinting it.
Route::get('/produits/{produit}','ProduitController#show');
public function show(Produit $produit)

Post not deleting, server error 500 in laravel 7

Please what am I doing wrong, Paymentdetails refuse to delete instead, its loading server error.There's something wrong with my code.
This is my controller
public function destroy(Paymentdetail $paymentdetail)
{
// dd($id);
if(Auth::user()->role_id == '1'){
$this->paymentdetails->delete($paymentdetail->id);
event(new Deleted($paymentdetail));
return redirect()->route('paymentdetails.index')
->withSuccess(__('Payment details deleted successfully.'));
}
else{
return redirect()->back()
->withErrors(__('Sorry! You Are Not Authorized To Delete Payment Details.'));
}
}
index.blade
<a href="{{ route('paymentdetails.edit', $paymentdetail) }}"
class="btn btn-icon edit"
title="#lang('Edit Paymentdetail')"
data-toggle="tooltip" data-placement="top">
<i class="fas fa-edit"></i>
</a>
<a href="{{ route('paymentdetails.destroy', $paymentdetail) }}"
class="btn btn-icon"
title="#lang('Delete Paymentdetail')"
data-toggle="tooltip"
data-placement="top"
data-method="DELETE"
data-confirm-title="#lang('Please Confirm')"
data-confirm-text="#lang('Are you sure that you want to delete this payment details?')"
data-confirm-delete="#lang('Yes, delete details!')">
<i class="fas fa-trash"></i>
</a></a>
Moved my answer from comments"
$this->paymentdetails->delete($paymentdetail->id);
seems over-engineered and confusing
$paymentdetail is instance of Paymentdetail and it extends Laravel Model. As it is instance of model - it knows how to find itself in DB therefore you can call
$paymentdetail->delete();
and instance will delete itself
First check your request method,it should be Get method.
iF method is Get then is it redirecting to given function?
You should on debug mod of laravel which gives you proper error.
Another thing check is user authenticated?

PHP routing: The GET method is not supported for this route. Supported methods: POST

I have an HTML form defined as follows:
<form action="{{route('save.checkout')}}" method="POST">
{{csrf_field()}}
<input name="amount" type="hidden" value="{{session()->get('cart')->totalprice}}">
<div class="cart_navigation">
<a class="continue-btn" href="#">
<i class="fa fa-arrow-left"> </i> خرید را ادامه دهید
</a>
<a class="checkout-btn" href="{{route('save.checkout')}}">
<i class="fa fa-check"></i> ادامه به پرداخت
</a>
</div>
</form>
The following error is being thrown when submitting the form:
The GET method is not supported for this route. Supported methods: POST.
my route is:
route::post('/savecheckout','BasketController#checkout')->name('save.checkout');
and the checkout function:
public function checkout(Request $request){
$user = auth()->user()->id;
$order = new order();
$order->user_id = $user;
$order->amount = $request->input('amount');
$order->status = 0;
$order->save();
$order = order::where('status' ,0)->where('user_id', $user)->first();
return view('checkout.index', compact('order'));
}
i solved the problem . it was a silly mistake i changed my button type to submit
if you are beginning with Laravel so i would like to contribute something to make your programming better & safer for future projects.
always validate your input
use of try & catch blocks
show appropriate error message to your users so that you can also
debug it in future.
so the modified code will be look like:
public function checkout(Request $request){
// use Validator; (add this after namespace to import validator)
$validator = Validator::make($request->all(),[
'user_id' => 'required|integer|max:11',
'amount' => 'required|numeric',
'status' => 'sometimes|integer|max:1',
]);
if($validator->fails()) {
return back()->withErrors($validator);
}
try {
$user = auth()->user()->id;
$order = new order();
$order->user_id = $user;
$order->amount = $request->input('amount');
$order->status = 0;
$order->save();
$request->session()->flash('message', 'Order Successfully Created');
$order = order::where('status' ,0)->where('user_id', $user)->first();
return view('checkout.index', compact('order'));
} catch (\Exception $e){
dd($e->getMessage()); // it will show the error message with, you can replace this block with redirect code or anything else..
}
}
for showing error & success message in front-end use below code in your checkout > index.blade.php template (just a sample code, you can make it more better by using your own CSS & styles)
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
#if(count($errors) > 0)
<div class="note note-error">
<h4>Error..!!</h4>
<p>
#foreach($errors->all() as $error)
<div class="alert alert-danger fade in m-b-15">
<i class="fa fa-chevron-right"></i>
{{ $error }}
<span class="close" data-dismiss="alert">×</span></div>
#endforeach
</p>
</div>
#endif

How to limit delete acces from direct link?

I have 2 questions and I need your help.First of all, I have made a delete route for comments, but other users logged can also delete comments from direct link...link.com/deleteComment/id. How to make this available only for owner of the comment?The owner id is saved in database and can be accessed with {{ $comment->user_id }}.
Second problem...In my view, when I click on a photo which have no comments, I'm receiving undefined variable comment, but I dont know why because on photos with comments, I have no problem with that.Can I make something like if comments != empty, dont show it or something like that?
CommentsController:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = Auth::user()->username;
$comment->email = Auth::user()->email;
$comment->user_id = Auth::user()->id;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
PostsController:
public function delete($id){
DB::table('posts')->where('id',$id)->delete();
return redirect('/profile/' . auth()->user()->id);
}
My view
#foreach($post->comments as $comment)
<div class="comment d-flex ">
<p><strong><a class="text-dark" href="/profile/{{ $comment->user_id }}">{{ $comment->username}}</a>: </strong> {{ $comment->comment}}</p>
#can('update', $post->user->profile)
<div class="dropdown col-md-6">
<button type="button" class="btn btn-primary dropdown-toggle btn-sm" style="background-color: #ffffff00;border: 1px solid #555;color: black;padding: 0 5px" data-toggle="dropdown">
Select
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Edit comment</a>
<a class="dropdown-item" title="Options" style="text-decoration: none;" href="/deleteComment/{{$comment->id}}">Delete comment</a>
</div>
</div>
</div>
#endcan
#endforeach
My route
Route::post('comments/{post_id}', ['uses' => 'CommentsController#store', 'as' => 'comments.store']);
Route::get('/deleteComment/{id}', 'CommentsController#delete');
Try this to restrict the deletion only for the authenticated user who owns the comment:
/**
* Comments Controller Method Delete
*/
public function delete($id){
if(!DB::table('comments')->where('id',$id)->where('user_id',auth()->user()->id)->delete()){
Session::flash('remove', "You do not have permission to delete the comment!");
}else{
Session::flash('remove', "Message removed successfully!");
}
return Redirect::back();
}
For your second question, I think that what happens is that by not having comments you are using the variable without results.
You can try to enclose the statement where you use the variable $comments using this.
For Controller or others files php
if (!$comment->isEmpty()) {
//your code
}
if ($comment->count()) {
//your code
}
if (count($comment)) {
//your code
}
For Blade
#if(!$comment->isEmpty())
//your code
#endif
#if($comment->count())
//your code
#endif
#if(count($comment))
//your code
#endif
I hope I could help you, if not, please attach more code where they appear exactly what he says, since comments and delete the picture, since I have not seen in the code you have attached. Thanks and good luck.
References
$comment->isEmpty
$comment->count() and count($comment)
Updated
<div class="row">
<div class="col-md-12">
#if(!$post->comments->isEmpty()) //****Added
#if($post->comments->count() > 0)
#foreach($post->comments as $comment)
<div class="comment d-flex ">
<p><strong><a class="text-dark"
href="/profile/{{ $comment->user_id }}">{{ $comment->username}}</a>:
</strong> {{ isset($comment->comment) ? $comment->comment : "--" }}</p>
#can('update', $post->user->profile)
<div class="dropdown col-md-6">
<button type="button" class="btn btn-primary dropdown-toggle btn-sm"
style="background-color: #ffffff00;border: 1px solid #555;color: black;padding: 0 5px"
data-toggle="dropdown">
Select
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Edit comment</a>
<a class="dropdown-item" title="Options" style="text-decoration: none;"
href="/deleteComment/{{$comment->id}}">Delete comment</a>
</div>
</div>
</div>
#endcan
#endforeach
#endif
#endif //****Added
</div>
</div>
Updated for delete if admin or no
/**
* Comments Controller Method Delete
*/
public function delete($id)
{
$comment = DB::table('comments')->where('id', $id):
if(!auth()->user()->admin){
$comment->where('user_id', auth()->user()->id);
}
if (!$comment->delete()) {
Session::flash('remove', "You do not have permission to delete the comment!");
} else {
Session::flash('remove', "Message removed successfully!");
}
return Redirect::back();
}
The first question can be done easily. In your destroy() function, just check comment owner:
// Check comment owner
if($comment->user_id != \Auth::id()){
return abort(401);
}
// Do logic code to delete comment.
The second question, you can check exist comment like this :
if(! $comments->isEmpty()) {
// Do logic code to show comment
}

Laravel Undifined Variable in View

I cant't figure out what's going wrong with a link from my "welcome" page to a "profile" page.
It says "Undefined variable: restaurants (View: /Users/beyerdynamic/Documents/Developer/dev1/resources/views/welcome.blade.php)"
The strange thong is that I pass the Variable to my view.
My PagesController is:
public function welcome() {
$restaurants = User::orderByRaw('RAND()')->take(3)->get();
return view('welcome')->withRestaurants($restaurants);
}
My View is:
#foreach($restaurants as $key => $restaurant)
<div class="col-md-4">
<div class="card">
<div class="image">
<img src="{{asset('images/frontend/profile/dummy/profilehero/hero4.png')}}" alt="..." />
<div class="filter filter-white">
<a href="{{ URL::to('profile/'.$restaurant->id)}}" type="button" class="btn btn-info btn-round btn-fill">
<i class="fa fa-heart"></i> View Restaurant
</a>
</div>
</div>
</div>
</div>
#endforeach
The Restaurants Variable is passed properly to my welcome view, but when I click the link the error occurs on /profile/{id} url.
Change return view('welcome')->withRestaurants($restaurants);
to
return view('welcome')->with('restaurants', $restaurants);
OR
return view('welcome', compact('restaurants');
Try with this,
return view('welcome')->with("restaurants",$restaurants);
OR
return view('welcome',["restaurants" => $restaurants]);
Check laravel docs : https://laravel.com/docs/master/views#passing-data-to-views
Change the following line:
return view('welcome')->withRestaurants($restaurants); // there is nothing like withRestaurants in laravel
to
return view('welcome', array('restaurants' => $restaurants));
and try again.

Categories