I am very new to laravel and I am really terrible with routing. I want to delete the specific data but it say that route is undefined
CandidateController.php
this is my method to delete
public function destroy(Form $candidates)
{
$candidates->delete();
return redirect()->route('candidate.approve');
}
route
Route::resource('candidates', CandidateController::class);
I am using a resourse, when I go through the tutorial, it shortened my code into above. When I clicked the button delete, it says that Undefined route [candidate.approve]. Can someone help me where I went wrong?
blade
#foreach ($candidates as $candidate)
<div class="modal__content">
<div class="p-5 text-center"> <i data-feather="x-circle" class="w-16 h-16 text-theme-6 mx-auto mt-3"></i>
<form action="{{ route('candidates.destroy', $candidate->id) }}" method="POST">
#csrf
#method('DELETE')
<div class="text-3xl mt-5">Are you sure?</div>
<div class="text-gray-600 mt-2">Do you really want to delete these records? This process cannot be undone.</div>
<button type="button" data-dismiss="modal" class="button w-24 border text-gray-700 dark:border-dark-5 dark:text-gray-300 mr-1">Cancel</button>
<button type="submit" title="delete" class="button w-24 bg-theme-6 text-white" >Delete</button>
</div>
<div class="px-5 pb-8 text-center">
</div>
</div>
</form>
</div>
#endforeach
web.php
Route::get('application/approve/{id}', 'CandidateController#postApprove')->name('application');
Route::get('candidate', [CandidateController::class, 'approve'])->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
Just add new Route with candidate.approve name before Route::resource.
your web.php file will be like this
Route::get('your-url', [CandidateController::class, 'approve')->name('candidate.approve');
Route::resource('candidates', CandidateController::class);
But its better to use prural for named route, like the resource controller :
candidates.create
candidates.store
...
UPDATE
Since i know the flow of the app, you should use this on controller:
return back();
Why? because when admin click Delete on modal, it will goes to another URL to delete data from DB. After delete, return back() will redirect admin to previous URL
Related
I've implemented a modal type Update and Delete functions in my website but it always return Too few arguments to function App\Http\Controllers\AdminController::destroy(), 1 passed in D:\SUDRTest\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
it is also the same for the Update function as well
Here is my route for the CRUD
Route::resource('papers', AdminController::class)->only(['edit', 'update', 'destroy']);
Here is the View
<li class="pdfpaperInfo">
<div class="colpdf col-1" data-label="Title:">{{ $paper->PaperTitle }}</div>
<div class="colpdf" data-label="Paper Type:">{{ $paper->PaperType }}</div>
<div class="colpdf" data-label="College:">{{ $paper->College }}</div>
<div class="colpdf" data-label="Author(s):">{{ $paper->Authors }}</div>
<div class="colpdf" data-label="Date Published:">{{ $paper->DatePublished }}</div>
<div class="pdfbtnCont">
<button class="pdfBtn redBtn" onclick="location.href='{{route('MyProfile')}}'">Back</button>
<button class="pdfBtn redBtn" id="modalOneBtn" onclick="location.href='{{route('papers.edit', $paper->PaperID)}}'">Update</button>
<button class="pdfBtn redBtn" id="modalTwoBtn">Delete</button>
</div>
</li>
<div id="modalOne" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m1Close close">×</span>
<div class="modalinfoCont">
<h2>Update Paper</h2>
#include('admin.updatepaper')
</div>
</div>
</div>
<div id="modalTwo" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="m2Close close">×</span>
<div class="modalTwoCont modalinfoCont">
<h2>Delete Paper</h2>
<br>
Are you sure you want to delete this paper?
<br>
<br>
<div class="modalbtnCont">
<form method="POST" action="{{route('papers.destroy', $paper->PaperID) }}">
#csrf
#method('DELETE')
<button class="redBtn" type="submit">Yes</button>
</form>
<button class="redBtn" type="submit">No</button>
</div>
</div>
</div>
</div>
</div>
and the controller
public function destroy(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
$paper->delete();
return redirect()->back();
}
public function edit(Papers $paper, $PaperID)
{
$paper=Papers::find($PaperID);
return view('admin.updatepaper',compact('paper'));
}
public function update(Request $request,Papers $paper, $PaperID )
{
$request->validate([
'PaperTitle' => 'required',
'PaperType' => 'required',
'file' => [
'required',
File::types('pdf')
->max(12 * 1024),
],
]);
$paper=new Papers();
$file=$request->file;
$filename=time().'.'.$file->getClientOriginalExtension();
$request->file->move('assets', $filename);
$paper->file=$filename;
$paper->DatePublished=$request->DatePublished;
$paper->PaperTitle=$request->PaperTitle;
$paper->PaperType=$request->PaperType;
$paper->Authors=$request->Authors;
$paper->update();
return redirect()->back();
}
I've tried not to do it in modal form and still it kept on displaying the same error and I don't know what is the missing parameter since it doesn't tell me
You need to take another look at route-model binding.
Laravel will by default do the Papers::find($paperID) and pass the Papers model as the Papers $papers argument to your methods.
So the destroy method should be:
public function destroy(Papers $paper)
{
$paper->delete();
return redirect()->back();
}
Of course you can disable route-model binding and do your own thing but it doesn't seem necessary here.
Its not clear what you intend to do in the update method. If you want to create a new paper on update and keep the old one then change $paper->update() to $paper->save() and you should be good. But if you want to do an actual update you should do something like this:
update(Papers $paper, Request $request) {
// validate
$paper->DatePublished=$request->DatePublished;
// update other fields
$paper->save();
return redirect()->back();
}
I've made a blog and now I'm trying to implement a comment section. I want it so that when the user tries to post, it's saves the comment and redirects the user to the same page. But when I write a comment and try to post it, the application redirects me to a different page. I'm learning how to make a blog with laravel, so I don't know when to use url and when to use routes. Here's the code that I've written.
#auth
<div class="card ml-5 col-lg-8">
<ul class="list-group list-group-horizontal">
<h5 class="list-group-item active">
Comments
<h5>
<div class="card-body">
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'.$blog->id)}}">
#csrf
<textarea name="comment" class="form-control py-5"></textarea>
<input type="submit" class="btn btn-primary mt-3">
</div>
</ul>
</div>
#endauth
<div class="card ml-5 col-lg-8">
<h5 class="card-header mb-4">Comments<span class="badge badge-info ml-2"> {{count($blog->comments)}}</span></h5>
<div class="card-body mt-3">
#if($blog->comments)
#foreach($blog->comments as $comment)
<blockquote class="blockquote">
<p class="mb-0">{{$comment->comment}}</p>
<footer class="blockquote-footer">Username</footer>
</blockquote>
<hr>
#endforeach
#endif
</div>
</div>
BlogController :
function save_comment(Request $request,$slug,$id)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
Routes :
Route::get('/blog/', [App\Http\Controllers\BlogController::class, 'index'])->name('blog');
Route::get('blogs/{slug}','App\Http\Controllers\BlogController#getArticles')->name('article.show');
Route::get('blog.update/{id}','App\Http\Controllers\BlogController#edit');
Route::put('blog.update/{id}','App\Http\Controllers\BlogController#update');
Route::post('save_comment/{slug}/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
Route::get('/admin/blog', 'App\Http\Controllers\BlogController#getBlog')->name('admin.blog');
If there's someone willing to assist come up with a solution to this problem, please assist me. I think the problem lies where I've written the url lies. When I change the url to route, it gives me an error of route not defined.
Route::resource('/blog','App\Http\Controllers\BlogController');
It redirects you to an empty page because you made a mistake on the url of your route. In your web.php file, your route is :
Route::post('save_comment/{slug}/{id}', 'App\Http\Controllers\BlogController#save_comment')->name('save_comment');
While in your form you wrote save-comment/ :
<form method="post" action="{{url('save-comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
The error is due to this. I therefore advise you to modify the action in your form like this save_comment/:
<form method="post" action="{{url('save_comment/'.Str::slug($blog->title).'/'. $blog->id)}}">
This should be fixed !
Please change your code like this and check...
action="{{route('save_comment', $blog->id])}}"
Route::post('save_comment/{id}','App\Http\Controllers\BlogController#save_comment')->name('save_comment');
**BlogController**
function save_comment($id, Request $request)
{
$request->validate([
'comment'=>'required',
]);
$data = new Comment;
$data->user_id=$request->user()->id;
$data->post_id=$id;
$data->comment=$request->comment;
$data->save();
return back();
}
I'm making a "teacher's" app, and I want to make a log-in page which changes depending if there's registered users in the database or not.
I want to make a redirection button to a create user page if there aren't auth users in database, and to make a select user view if the database have one or more users.
The problem is that I don't know how to exactly do this, 'cause the view always shows me the first statement (what I've got in the if), also if in the database are registered users. Can anyone help me with this please?
This is the blade file:
#if (empty(Auth::user()->id))
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
Here you have the controller index method:
public function index()
{
$users = User::all();
return view('/', compact('users'));
}
And finally here you have the page:
The following code is the sample for it, kindly replace code accordingly
#if(!$user)
//show button
#else
//dont show button
#endif
I think your question is you want to check if there is user in database.
So no need to check if the user authenticated but to check if there is user on the database.
In your controller
public function index() {
return view('/', ['users' => User::all()]);
}
and in your blade file
#if(!$users)
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Welcome</h1>
<p>We see there aren't users</p>
</div>
<div id="loginForm">
<button type="button" onclick="window.location='{{ url("/newUser") }}'">Button</button>
</div>
</div>
#else
<div class="grid-item" id="grid-item5">
<div id="title">
<h1>Select an user</h1>
</div>
<div id="loginForm"></div>
</div>
#endif
This function will get the current authenticated user: Auth::user(). I guess what you are trying to achieve is #if(empty($users)) where $users is the variable you are passing on controller.
If you want to verify if the user that accessed to that view is authenticated you can simply use #auth and #guest.
Also i would suggest you to change your button to an <a> tag and your href would be <a href="{{ route('route.name') }}" where route.name would be defined in your routes file.
in your controller:
you can create a folder inside views called users and then the index.blade.php (views/users/index.blade.php)
public function index()
{
$users = Users::all();
return view('users.index')->with('users', $users);
}
in your view:
#if(count($users) < 1)
...
#else
...
#endif
count is validating if the $users array length is less then 1 (in other words if the array is empty).
Alternative you can you isEmpty()
#if($users->isEmpty())
...
#else
...
#endif
I have a web app project I've been working on, most of the applications functionality works except for submitting a flag on a resource. I want to use a modal form to submit the data to the database, then on the Flagged view page display all flagged resources Name & Description(from the Resources table) Flag_Reason & Other_Comments(from the Flagged table) I had it working to where it was submitting only the Flag_Reason and Other_Comments and not updating my Resources Table at all. I believe I'm having issues with routes now, because after changing my function to update my Resources table AND create a new Flag entry in the DB I get an error like this
Missing argument 1 for App\Http\Controllers\FlagsController::addFlag()
Here's some of my code, hopefully someone can help me finally figure this out once and for all.
Routes
Route::get('resource', array('as'=>'viewResource', 'uses' => 'ResourceController#resource'));
Route::get('flags', 'FlagsController#index');
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
///Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#postFlag']);///
This route works fine, and only inserts the Flagged table data into the database.
If I modify my route to look like this Route::post('resource/{Resource_ID}', ['as' => 'resource', 'uses'=>'FlagsController#addFlag'])
I receive an error like this
Missing required parameters for [Route: resource] [URI: resource/{Resource_ID}].
Flags Controller
class FlagsController extends Controller
{
public function index()
{
$resources = Resources::where('Flagged', 1)->with('flags')->get();
return view('pages.flags', ['resource' => $resources]);
}
public function addFlag($id)
{
$flag = Flagged::create(Request::all());
$resource = Resources::findOrFail($id);
$resource->update(array('Flagged' => 1));
$resource->flags()->attach([$flag->id]);
dd($resource::all());
return back();
}
//////// This function inserts only the Flagged table data into the Flagged table, It doesnt do what I want it to do, so i've commented it out/////
public function postFlag()
{
$flag = Flagged::create([
'Flag_Reason' => Input::get('reason'),
'Other_Comments' =>Input::get('comments')]);
$flag->save();
\Session::flash('flash_message', 'Flagged!');
return redirect('resource');
}
}
Resource View
...
#foreach($resources as $resource) #foreach ($resource->locations as $location)
<tr>
<td> <a class="btn btn-small btn-default" style="float:right; margin-right:5px;" href="{{ URL::to('resource/addToCart/' .$resource->Resource_ID) }}">+</a> {{ $resource->Name }}</td>
<td>{{ $resource->Description }}</td>
<td>{{ $location->Address }}</td>
<td>{{ $location->City }}</td>
<td>{{ $location->Zip_Code }}</td>
<td>{{ $location->County }}</td>
<td>
<button type="button" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Edit
</button>
<button type="button" id="submitFlag" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Flag
</button>
<button type="button" class=" msgBtn3 btn btn-default pull-right" style="display:inline; margin-right:auto;">Delete
</button>
</td>
</tr>
#endforeach
#endforeach
Modal, inside the Resources View
<div class="modal fade" id="flagResource" tabindex="-1" role="dialog" aria-labelledby="flagModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title"
id="flagResourceLabel" style="text-align:center;"> Flagged
</h4>
</div>
<div class="modal-body">
{!! Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}
<div class="form-group">
<label for="reason" class="control-label">Reason for Flagging:</label>
{!! Form::text('reason', null, array('class'=> 'form-control', 'placeholder'=>'Reason')) !!}
</div>
<div class="form-group">
<label for="comments" class="control-label">Other Comments:</label>
{!! Form::text('comments', null, array('class'=> 'form-control', 'placeholder'=>'Comments')) !!}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<span class="pull-right">
<button id="submitFlag" type="submit" class="btn btn-primary" style="margin-left:5px;">Flag</button>
</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script>
$('#flagResource').on('show.bs.modal', function(e) {
//var submitFlag = $(e.relatedTarget);
var resourceName = $(e.relatedTarget).data('resource-name');
var resourceId = $(e.relatedTarget).data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
});
</script>
The problem I think is happening is my form open inside my modal
{!! Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}, and my addFlag function accepts an ID, but my resource route doesn't need an {id} on it.
If someone could take a look at my routes and help me debug it, it would be great. Thanks in advance.
You need to keep the route how you had it so it passes the Resource_ID but then you need to also pass it when you setup your form.
{!! Form::open(array('route'=>'resource' array('Resource_ID' => $yourId), 'class'=>'form', 'method'=>'POST')) !!}
Regarding your comment, and looking closer at your code, I think it might make sense to re-consider how this works.
You are passing multiple resources to this view so I think adding the resource id to the URL like I originally suggested is not the best idea because it needs to be dynamic depending on what resource was clicked on and the URL isn't the easiest thing to change via javascript.
I think a better solution would be to go back to using Form::open(array('route'=>'resource', 'class'=>'form', 'method'=>'POST')) !!}, then removing the /{Resource_ID} portion from your route and also removing the $id from public function addFlag() since we are no longer passing it via the URL.
Then in your form, add a hidden valid for resource_id
<input type="hidden" name="resource_id" id="resource_id" value="" />
Then you are already listening for the bootstrap show event and grabbing the right resource id, we just need to add it to the value.
$('#flagResource').on('show.bs.modal', function(e) {
//var submitFlag = $(e.relatedTarget);
var resourceName = $(e.relatedTarget).data('resource-name');
var resourceId = $(e.relatedTarget).data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
$('#resource_id').val(resourceId);
});
No in your addFlag() method, you can grab the resource id via...
$id = \Input::get('resource_id');
Your addFlag function inside FlagsController accepts a parameter called $id the exception you are receiving is because you have forgotten to add the parameter to your route.
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
Should Be
Route::post('resource/{id}', ['as' => 'resource', 'uses'=>'FlagsController#addFlag']);
I believe Laravel Route parameters are name specific which is why {Resource_ID} does not work.
You can read more about routing with parameters in Laravel here
As for your modal inside the resources view you need to also pass the parameter of the resource you're updating on the form
{!! Form::open(array('route'=>'resource', array('id' => $yourIdHere), 'class'=>'form', 'method'=>'POST')) !!}
Make sure to replace $yourIdHere with the resource you want to up.
Everything else appears to be in order.
In my application, I've always been able to pass data to any view as one would normally do using view('myView', compact('data'));. As of today, any view I try to render this way times out. I'm getting the error Maximum execution time of 120 seconds exceeded in Whoops!. I tried increasing php.ini and httpd.conf timeout times but no cigar. It's really odd and it doesn't make sense to me because I've always been able to render my views almost instantly, even when retrieving 15k+ records from the database and passing them to the view like I've always done.
My controller:
use App\Product;
use Illuminate\Support\Facades\Session;
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
//the controller is normally like this
//$products = Product::paginate(16);
//return view('home', compact('products'));
//I'm testing with these 2 lines below but no cigar.
$product = Product::wherePid(303)->first();
return view('test', compact('product'));
}
}
The test view I created:
#extends('app')
#section('content')
{{ $product->name }}
#stop
My application view:
#extends('app')
<pre>{{ var_dump(Session::all())}}</pre>
#section('content')
<div class="row">
#foreach($products as $product)
<div class="col-xs-6 col-sm-3 col-lg-3 col-md-3">
<?php
if($product->img[7] == 'm' || $product->img[7] == 'M') echo "<div class='continenteIcon'></div>";
else echo "<div class='jumboIcon'></div>";
?>
<div class="thumbnail">
<a href="products/{{$product->pid}}"><img src="{{$product->img}}" title="
<?php
if($product->dispname != '') echo $product->dispname;
else echo $product->name;
?> ">
</a>
<div class="caption">
<h4>
<a style="text-decoration:none;" class="wordwrap" title="
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;
?>" href="products/{{$product->pid}}">
<?php
if($product->dispname != '')
echo $product->dispname;
else echo $product->name;?>
</a>
</h4>
<p>{{$product->brand}}</p>
<span class="pull-right price">€{{$product->price}}</span>
<br/>
<span class="pull-right ppk">€{{round($product->pricekilo, 2)}} Kg, L ou Und</span>
</div>
<div class="ratings">
<p class="pull-right"> {{-- # review--}}</p>
<p>
<form method="post" action="add/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Adicionar ao carrinho" type="submit" class="btn btn-success">
<i class="fa fa-shopping-cart"></i>
</button>
</form>
<form method="post" action="products/related/{{$product->pid}}">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button title="Ver artigos semelhantes" style="position:relative; bottom:35px;" type="submit" class="btn btn-info pull-right">
<i class="fa fa-search"></i>
</button>
</form>
</p>
</div>
</div>
</div>
#endforeach
</div>
<div class="row">
{!! $products->render() !!}
</div>
<div class="row">
<div class="pull-right">
* Preço por unidade, Litro ou Kilograma
</div>
#stop
#section('scripts')
#stop
The problem doesn't only happen in this view, but every single time I try to fecth someting from the database and pass it to the view to render. I keep getting timeouts and I can't seem to fix it no matter what I do.
I am clueless why this is happening. It seems like it started out of the blue. I have no Idea what could be causing this issue.
Any help?
P.S.: I'm using Wamp.
EDIT: I forgot to add something that might be important:
Everything is up and running in Wamp. If I dd() out the query result and do not render the view
$products = Product::paginate(16);
dd($products);
//return view('home', compact('products'));
this is fast, as it always used to be. And by fast I mean it takes less than 1 second to retrieve everything I need. But if I render the view with
return view('home', compact('products'));
everything just stalls and I get a 500 (I checked with Fiddler2 and after the page stops loading, the request status is 500)
It seems like you may be requesting too many records which may be using too much of your RAM. I would use the chunk command to help you with managing the amount you're requesting.
For example:
User::chunk(200, function($users)
{
foreach ($users as $user)
{
//
}
});
First check logs.
Next try to dd($product)
Next if you try to render view with last 2 lines (getting first record) remove pagination from template.
Clean template to minimum e.g.
#extends('app')
#section('content')
<div class="row">
#foreach($products as $product)
#endforeach
</div>
#stop
I just sorted it out. The issue was in the following block of code in app.blade.php.
$size = Session::get('size');
...
<input type="text" value="'.Session::get($item).'">
...
I was messing around with data from an existing session and everything was working fine. I assumed I was doing it right. I wasn't. Not by a chance :)
Assumption is the mother of all screw ups.
Surrounded the whole block with if(Session::has('size') and everything is blazing fast and running smoothly as usual.
Thanks #Pyton for pointing me out into the right direction and thanks everyone for your contribution.