Edit: I think this problem is due to not setting up apache properly, these two links helped me.
Solution:
http://laravel.io/forum/06-11-2014-not-found-but-route-exists
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts
End Edit
I'm following the Laravel 5.2 quickstart guide. https://laravel.com/docs/5.2/quickstart
I'm running ubuntu 14.04.2
The website runs initially, but then when I click on the add Task button
I run into a 404 Not Found error.
As per the guide I run the following commands to setup the complete quickstart project.
git clone https://github.com/laravel/quickstart-basic quickstart
cd quickstart
composer install
php artisan migrate
Additionally I run the following commands because I'm on an ubuntu server:
sudo chown -R www-data.www-data quickstart
sudo chmod -R 755 quickstart
sudo chmod 777 quickstart/storage
The routes.php file looks like:
<?php
use App\Task;
use Illuminate\Http\Request;
Route::group(['middleware' => ['web']], function () {
//
Route::get('/', function () {
$tasks = Task::orderBy('created_at', 'asc')->get();
return view('tasks', [
'tasks' => $tasks
]);
});
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
//
Route::delete('/task/{task}', function (Task $task) {
$task->delete();
return redirect('/');
});
});
I tried changing some code in the resources/view/tasks.blade.php from:
<!-- New Task Form -->
<form action="/task" method="POST" class="form-horizontal">
To the location of the actual public folder of the laravel project :
<!-- New Task Form -->
<form action="/learninglaravel/laraquickstart/quickstart/public/task" method="POST" class="form-horizontal">
So my problem is only when I press the button I get a 404 Error
//***** Edit:
I have tried having editing the post route but that doesn't fix the problem.
Route::post('/learninglaravel/laraquickstart/quickstart/public/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
The error is:
Not Found
The requested URL /learninglaravel/laraquickstart/quickstart/public/task was not found on this server.
Instead of:
Not Found
The requested URL /task was not found on this server.
I did what you suggested James and you were right, it makes the URL change to
/learninglaravel/laraquickstart/quickstart/public/task
but I still get the error of page not found. The only difference is the error message changed from the bellow error to the above. (I also tried manually changing both the url in the route.php file and the tasks.blade.php to reflect the same url. So the above URL would be both in the routes.php and the tasks.blade.php
I'm running on an ubuntu AWS server maybe I made a mistake on that end? I think the quickstart tutorial was written for homestead as I ran into problems with the database.(I just had to manually create one. The guide never specified that. I think it might be pre-configured in homestead to automatically use a database)
Cheers
From the guide on Quickstart, you can generate your form action URLs using the url helper, which:
generates a fully qualified URL to the given path.
As such you can use it like so on your form:
<!-- New Task Form -->
<form action="{{ url('task') }}" method="POST" class="form-horizontal">
This will ensure you are always posting to the correct URL for your domain, without you having to specify this yourself manually.
Give it a go and see what I mean, but in your case it would generate a url for you to your task route along the lines of this (based off your comment); 52.60.22.45/learninglaravel/laraquickstart/quickstart/public/task
When you change your form action parameter to
/learninglaravel/laraquickstart/quickstart/public/task
You are going to make HTTP POST request to
{scheme}://{domain}//learninglaravel/laraquickstart/quickstart/public/task
So laravel is going to look for this route and obviously it won't find it.
Just enabled mod_rewrite engine and it will work perfectly.
I have spend more then 2 hrs to find the solution and the solution. So don't wast your time and just enable the mod_rewrite engine by following command and try again:
sudo a2enmod rewrite
And dont forget to restart the apache server
sudo /etc/init.d/apache2 restart
or
sudo service apache2 restart
Related
Im trying to do a POST request with jQuery but im getting a error 405 (Method Not Allowed), Im working with Laravel 5
THis is my code:
jQuery
<script type="text/javascript">
$(document).ready(function () {
$('.delete').click(function (e){
e.preventDefault();
var row = $(this).parents('tr');
var id = row.data('id');
var form = $('#formDelete');
var url = form.attr('action').replace(':USER_ID', id);
var data = form.serialize();
$.post(url, data, function (result){
alert(result);
});
});
});
</script>
HTML
{!! Form::open(['route' => ['companiesDelete', ':USER_ID'], 'method' =>'DELETE', 'id' => 'formDelete']) !!}
{!!Form::close() !!}
Controller
public function delete($id, \Request $request){
return $id;
}
The Jquery error is http://localhost/laravel5.1/public/empresas/eliminar/5 405 (Method Not Allowed).
The url value is
http://localhost/laravel5.1/public/empresas/eliminar/5
and the data value is
_method=DELETE&_token=pCETpf1jDT1rY615o62W0UK7hs3UnTNm1t0vmIRZ.
If i change to $.get request it works fine, but i want to do a post request.
Anyone could help me?
Thanks.
EDIT!!
Route
Route::post('empresas/eliminar/{id}', ['as' => 'companiesDelete', 'uses' => 'CompaniesController#delete']);
The methodNotAllowed exception indicates that a route doesn't exist for the HTTP method you are requesting.
Your form is set up to make a DELETE request, so your route needs to use Route::delete() to receive this.
Route::delete('empresas/eliminar/{id}', [
'as' => 'companiesDelete',
'uses' => 'CompaniesController#delete'
]);
Your routes.php file needs to be setup correctly.
What I am assuming your current setup is like:
Route::post('/empresas/eliminar/{id}','CompanyController#companiesDelete');
or something. Define a route for the delete method instead.
Route::delete('/empresas/eliminar/{id}','CompanyController#companiesDelete');
Now if you are using a Route resource, the default route name to be used for the 'DELETE' method is .destroy. Define your delete logic in that function instead.
In my case the route in my router was:
Route::post('/new-order', 'Api\OrderController#initiateOrder')->name('newOrder');
and from the client app I was posting the request to:
https://my-domain/api/new-order/
So, because of the trailing slash I got a 405. Hope it helps someone
If you didn't have such an error during development and it props up only in production try
php artisan route:list to see if the route exists.
If it doesn't try
php artisan route:clear to clear your cache.
That worked for me.
This might help someone so I'll put my inputs here as well.
I've encountered the same (or similar) problem. Apparently, the problem was the POST request was blocked by Modsec by the following rules: 350147, 340147, 340148, 350148
After blocking the request, I was redirected to the same endpoint but as a GET request of course and thus the 405.
I whitelisted those rules and voila, the 405 error was gone.
Hope this helps someone.
If you're using the resource routes, then in the HTML body of the form, you can use method_field helper like this:
<form>
{{ csrf_field() }}
{{ method_field('PUT') }}
<!-- ... -->
</form>
It will create hidden form input with method type, that is correctly interpereted by Laravel 5.5+.
Since Laravel 5.6 you can use following Blade directives in the templates:
<form>
#method('put')
#csrf
<!-- ... -->
</form>
Hope this might help someone in the future.
When use method delete in form then must have to set route delete
Route::delete("empresas/eliminar/{id}", "CompaniesController#delete");
I solved that issue by running php artisan route:cache which cleared the cache and it's start working.
For Laravel 7 +, just in case you run into this, you should check if the route exists using
php artisan route:list
if it exists then you need to cache your routes
php artisan route:cache
For my application in october cms I'd like to be able to send a mail with the click of a button. I call the php file with an ajax request, however when the button gets clicked I get the error 'class not found' for whichever class I use, doesn't matter which. I already added the file to .htaccess to be able to run it on the button click. I included all classes at the top of the file. Also when I turn it into an artisan command and run it with php artisan now:send:mail it works without any issues. I already tried to run composer dump autoload and composer dump autoload -o. Code is down below, Any idea what I can do to make this work, or in what other way it could be done?
Thanks in advance!
Part of theme.js:
$.ajax({
url : '/plugins/test/notifications/ondemand/OnDemand.php'
}).done(function(data) {
console.log(data);
});
OnDemand.php:
<?php
namespace Test\Notifications\OnDemand;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Test\Poles\Components\Metrics;
use October\Rain\Argon\Argon;
class OnDemand
{
public function send()
{
$date = Argon::now(config('app.timezone'))->format('Y-m-d');
// get some data
$array = ['date' => $date, 'score' => $score, 'CO2' => $CO2, 'scorecar' => $scorecar, 'scorebike' => $scorebike];
$email = "test#test.nl";
Mail::sendTo($email, 'daily.mail', $array);
}
}
$mail = new OnDemand;
$mail->send();
I'm not sure whether you want to do this as part of a custom October plugin you've developed or simply inside a regular October template. However, the absolutely simplest way of having an ajax button to send an email would be as follows:
1) Create a new mail template in the October backend in Settings | Mail Templates
2) In the "CMS" section of October, create a new blank Page
3) For the "Markup" section of the new page, the button HTML:
<button data-request="onPressButton">Send</button>
4) For the "Code" section of the new page, the following PHP:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Test\Poles\Components\Metrics;
use October\Rain\Argon\Argon;
function onPressButton()
{
$date = Argon::now(config('app.timezone'))->format('Y-m-d');
// get some data
$array = ['date' => $date, 'score' => $score, 'CO2' => $CO2, 'scorecar' => $scorecar, 'scorebike' => $scorebike];
$email = "test#test.nl";
Mail::sendTo($email,'daily.mail', $array);
}
That's it. As long as you include JQuery and {% framework extras %} in your October page layout, the above will work.
The principal is the same if you're adding this within a custom plugin that you've developed, but the HTML and PHP would obviously go into their individual files within a component if you did it that way.
I'm working on a web application using Laravel 5.8, I'm new to Laravel framework. I would like to display PDF documents on the browser when users click on some buttons. I will allow authenticated users to "View" and "Download" the PDF documents.
I have created a Controller and a Route to allow displaying of the documents. I'm however stuck because I have a lot of documents and I don't know how to use a Laravel VIEW to display and download each document individually.
/* PDFController*/
public function view($id)
{
$file = storage_path('app/pdfs/') . $id . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->download($file, 'Test File', $headers, 'inline');
} else {
abort(404, 'File not found!');
}
}
}
/The Route/
Route::get('/preview-pdf/{id}', 'PDFController#view');
Mateus' answer does a good job describing how to setup your controller function to return the PDF file. I would do something like this in your /routes/web.php file:
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
The other part of your question is how to embed the PDF in your *.blade.php view template. For this, I recommend using PDFObject. This is a dead simple PDF viewer JavaScript package that makes embedding PDFs easy.
If you are using npm, you can run npm install pdfobject -S to install this package. Otherwise, you can serve it from a CDN, or host the script yourself. After including the script, you set it up like this:
HTML:
<div id="pdf-viewer"></div>
JS:
<script>
PDFObject.embed("{{ route('show-pdf', ['id' => 1]) }}", "#pdf-viewer");
</script>
And that's it — super simple! And, in my opinion, it provides a nicer UX for your users than navigating to a page that shows the PDF all by itself. I hope you find this helpful!
UPDATE:
After reading your comments on the other answer, I thought you might find this example particularly useful for what you are trying to do.
According to laravel docs:
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.
All you need to do is pass the file path to the method:
return response()->file($pathToFile);
If you need custom headers:
return response()->file($pathToFile, $headers);
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
Or if file is in public folder
Route::get('/show-pdf', function($id='') {
return response()->file(public_path().'pathtofile.pdf');
})->name('show-pdf');
then show in page using
<embed src="{{ route('show-pdf') }}" type="text/pdf" >
I have noticed that I get this error a lot. Say I start creating a CRUD for a projects table, but in the Controller I only do index, create and show. I get everything working with these functions as they should be.
At a later point, say I decide to add an edit function, something simple like
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
If I then try to edit the project, I get
NotFoundHttpException in RouteCollection.php line 143:
Even if I simply return a String I get the same Exception. From experience, if I restarted my entire project and added the edit function from the start, then it would work without problem.
I have tried clearing caches, deleting files in the storage folder, everything I can think off. Nothing seems to work however. This project is now quite large, and I really do not want to start it again.
I have checked route:list and the route is there and its all pointing to the correct locations. If I select edit, the page that shows the error has a url like
http://localhost:8000/projects//edit
So it is missing the id between projects/ and /edit. If I manually enter the id, then the page displays fine.
Is there anything I can do to get rid of this error without having to restart my project?
Thanks
Update
My routes are done like so
Route::model('projects', 'Project');
Route::bind('projects', function($value, $route) {
return App\Project::whereId($value)->first();
});
Route::resource('projects', 'ProjectsController');
This is my link to edit
{!! link_to_route('projects.edit', 'Edit', array($project->slug), array('class' => 'btn btn-info')) !!}
And the Controller is
public function edit(Project $project)
{
$clients = Client::lists('clientName', 'id');
$users = User::lists('userName', 'id');
return View::make('projects.edit', compact('project', 'clients', 'users'));
}
My show works fine, and I am passing that a Project variable. As I say, it I redone my project with the edit in from the start, I know it will work (as I have done it before).
Thanks
When you create edit URL you need to pass id to create valid URL, in this case it should be for example projects/1/edit when you want to edit project with id=1. Otherwise you will get this NotFoundHttpException because in your routes there is no route projects//edit but there is probably route projects/{id}/edit
I'm creating an authorization system in my Laravel 4 project. I am trying to use the auth "before" filter.
In my routes.php file, I have:
Route::get('viewer', array('before' => 'auth', function() {
return View::make('lead_viewer');
}));
Route::get('login', 'LoginController');
The before filter calls this line in the filters.php file:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::route('login');
});
I can manually navigate to my login route. But the auth system isn't letting this happen. I've run composer dump-autoload a couple of times, so that isn't the problem. What am I doing, since I can actually load the login page if I do it manually?
I figure it out. Laravel is looking for a named route: I had to do this:
Route::get('login', array('as' => 'login', function() {
return View::make('login');
}));
An interesting, not very intuitive approach in Laravel. But there must be a reason Taylor did this that I'm not seeing.
To do what you were trying to do in your initial approach you could have just done:
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('/login');
});
and it would have worked just fine.
If you want to use named routes then you do what you posted in your answer to your own question. Essentially...more than one way to skin a cat.
Hope that helps
I know you've probably solved this by now but after stumbling across your post while trying to solve a similar problem, I wanted to share my thoughts...
Laravel is NOT looking for a named route for the guest method, it is expecting a path.
Your example works because because the named route and the path are the same i.e. "login". Try changing your URL to something other than 'login' and watch it fail.
If you want to use a named route you should use the route helper method as so...
if (Auth::guest()) return Redirect::guest( route('login') )
Hope that helps someone.