I am new to laravel and learning it now. I am giving following Route in routes.php file
Route::resource('contacts', 'ContactsController');
But when I load my page in browser, it gives me following error
Unhandled Exception
Message:
Call to undefined method Laravel\Routing\Route::resource()
Location:
/Users/zafarsaleem/Sites/learning-laravel/application/routes.php on line 35
My complete routes.php file is below
Route::resource('contacts', 'ContactsController');
Route::get('/', function() //<------- This is line 35
{
return View::make('home.index');
});
How can I remove this error?
Edit
ContactsController code is below and I want index() function to be used
class ContactsController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
Contact::all();
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::json();
Contact::create(array(
'first_name' => $input->first_name
'last_name' => $input->last_name
'email_address' => $input->email_address
'description' => $input->description
));
}
/**
* Display the specified resource.
*
* #return Response
*/
public function show($id)
{
return Contact::find($id);
}
/**
* Show the form for editing the specified resource.
*
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #return Response
*/
public function update($id)
{
$contact = Contact::find($id);
$input = Input::json();
$contact->first_name = $input->first_name;
$contact->last_name = $input->last_name;
$contact->email_address = $input->email_ddress;
$contact->description = $input->description;
$contact->save();
}
/**
* Remove the specified resource from storage.
*
* #return Response
*/
public function destroy($id)
{
return Contact::find($id)->delete();
}
}
Edit 2
I tried both following routes but ended up same below error
Route::resource('contacts', 'ContactsController', ['only', => ['index']]);
Route::get('contacts','ContactsController#index');
After reinstalling laravel 4 now I am getting following error
404 Not Found
The requested URL /contacts was not found on this server.
_____________________________________________________________________
Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch Server at bb.dev Port 80
Edit 3
Here is what did now, I edit "/private/etc/apache2/users/.conf" and changed from "AllowOverride None" to "AllowOverride All" and then restarted my apache server. Now I am getting following error
403 Forbidden
You don't have permission to access /contacts on this server.
__________________________________________________________________________________
Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch Server at bb.dev Port 80
Why don't I have permission for this contacts controller? It is making me crazy now.
Here is my .htaccess file
<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Have you tried this on another server? A lot of things can go wrong with rewriting (I've lost hours fixing the .htaccess), so the problem may be Apache and not Laravel.
This works for me in public/.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
And have you tried going to index.php/contacts instead of /contacts? If that works, the problem is Apache, not Laravel.
It may be a namespace issue -- it should be calling the function on Illuminate\Routing\Router but your exception refers to Laravel\Routing\Route::resource().
Is it possible that your configuration file still has references to Laravel3 in it?
Try changing your routes to
Route::resource('/contacts', 'ContactsController');
In ContactsController.php change index to return instance of the model
public function index()
{
return Contact::all();
}
I had the same $#%& issue, and after hours of searching I found it is not a problem of the .httacess file. What I just did to fix this:
composer update --dev
I think that the --dev bit is the important thing. Hope that helps someone.
ok i had the issue up to one minute ago!
it is because of ide-helper
to solve you should comment the following code in routes.php
use Illuminate\Routing\Route;
Related
I am trying to develop my own MVC and i got to the point where a routing system is due.
I have used some examples from the internet and partially it works fine. Evan so, i think something is wrong and i will detail it right bellow.
My MVC has a frontend and a backend. The first question is : Do i need to load the same routing system for the frontend and the backend? Or do i need to have different routing systems? How would you choose?
In the frontend, whenever i am using the main menu to navigate i can go to home or contact page and the pages are displaying corectlly - and the browser url - looks fine : localhost/home or localhost/contact (without the php extension - which is the desired behaviour.)
In the backend section of my website - reaching it by using localhost/admin - of course the routing system from my front-end section has some rules for the admin, so when i am reaching the admin section the browser url is fine - showing http://localhost/admin/ and displays some login form. The Login Form uses post to send info to another page- login.php which runs the login system, and if successfull requires a page named home.php. The problem is after the successfull login - the browser url is http://localhost/admin/login.php !!! which IS NOT the desired behaviour because i am expecting in fact localhost/admin/home (without the php extension) . i have tried with a different routing system for the backend - but for some reason it's not taken in consideration and i have also tried to include the routing system after the succesfull login. I cannot find a good solution. I am surely missing something and i do not know why so please help me. This is how my routing system is looking.
<?php
// Include router class
include('Route.php');
// Add base route (startpage)
Route::add('/',function(){
require 'pages/home.php';
});
// Simple test route that simulates static html file
Route::add('/contact',function(){
require 'pages/contact.php';
});
// Post route example
Route::add('/contact-form',function(){
echo '<form method="post"><input type="text" name="test" /><input type="submit" value="send" /></form>';
},'get');
// Post route example
Route::add('/contact-form',function(){
echo 'Hey! The form has been sent:<br/>';
print_r($_POST);
},'post');
// Accept only numbers as parameter. Other characters will result in a 404 error
Route::add('/foo/([0-9]*)/bar',function($var1){
echo $var1.' is a great number!';
});
Route::run('/');
My router Class:
class Router
{
/**
* The request we're working with.
*
* #var string
*/
public $request;
/**
* The $routes array will contain our URI's and callbacks.
* #var array
*/
public $routes = [];
/**
* For this example, the constructor will be responsible
* for parsing the request.
*
* #param array $request
*/
public function __construct(array $request)
{
/**
* This is a very (VERY) simple example of parsing
* the request. We use the $_SERVER superglobal to
* grab the URI.
*/
$this->request = basename($request['REQUEST_URI']);
}
/**
* Add a route and callback to our $routes array.
*
* #param string $uri
* #param Callable $fn
*/
public function addRoute(string $uri, \Closure $fn) : void
{
$this->routes[$uri] = $fn;
}
/**
* Determine is the requested route exists in our
* routes array.
*
* #param string $uri
* #return boolean
*/
public function hasRoute(string $uri) : bool
{
return array_key_exists($uri, $this->routes);
}
/**
* Run the router.
*
* #return mixed
*/
public function run()
{
if($this->hasRoute($this->request)) {
$this->routes[$this->request]->call($this);
}
}
}
and my successfull login statement which redirect to home :
if ($login) {
require './pages/home.php';
} else {
echo 'ERROR';
}
my htaccess from the admin section folder :
DirectoryIndex index.php
FallbackResource /index.php
# enable apache rewrite engine
RewriteEngine on
# set your rewrite base
# Edit this in your init method too if you script lives in a subfolder
RewriteBase /admin
# Deliver the folder or file directly if it exists on the server
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Push every request to index.php
RewriteRule ^(.*)$ index.php [QSA]
I'm watching a tutorial video from youtube about making simple route project with just php and I did exactly what he did but there is an error in my project and I can't fix that . when I'm trying to write 'about' or 'contact' the webpage went to object not found! error
Object not found!
The requested URL was not found on this server. If you entered the URL
manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.43 (Win64) OpenSSL/1.1.1g PHP/7.4.5
by the way I'm using xampp
This is my route class
class Route{
private $_uri = array();
/**
* Builds a collection of internal URL's to look for
* #param $uri
*/
public function add($uri){
$this->_uri[] = trim($uri,"/");
}
public function submit(){
$uriGetParam = isset($_GET['uri']) ? $_GET['uri'] : "/";
foreach ($this->_uri as $key => $value){
if (preg_match("#^$value$#",$uriGetParam)){
echo "Match!";
}
}
}
}
This is my php code (index)
include "route.php";
$route = new Route();
$route->add("/");
$route->add("/contact");
$route->add("/about");
$route->submit();
And finally this is my .htaccess file
RewriteEngine On
RewriteBase /route/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?uri=$1 [QSA,L]
I am new to Laravel, I am working over a small project, using wamp. I was facing problem with pretty URL part, which I figured it out just now.
But now I am getting a weird issue. I have created my application under directory laravel-first-app.
When I am trying to request a page (articles) for example, http://localhost/laravel-first-app/public/index.php/cv, it is showing up the page.
But now if, I request a page for example, http://localhost/laravel-first-app/public/cv, it is saying URL Not Found error.
Below is a brief description what I did.
In my routes.php
Route::get('/', 'WelcomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Route::resource('articles','ArticlesController');
Route::get('articles/delete/{article_id}','ArticlesController#destroy');
Route::get('cv','CvController#index');
Route::get('cv/upload','CvController#upload');
Route::post('cv','CvController#store');
In my CvController
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class CvController extends Controller {
private $pathToCV;
private $fileName;
public function __construct()
{
$this->pathToCV="cv/";
$this->fileName='piyush_cv.doc';
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return response()->download($this->pathToCV.$this->fileName);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function upload()
{
return view('cv.upload');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
dd($request);
if($request->hasFile('cv'))
{
$file = $request->file('cv');
$file->move($this->pathToCV,$this->fileName);
flash()->overlay('File Uploaded','Thanks for uploading the file');
return redirect('cv/upload');
}
flash()->overlay('File was not selected','');
return redirect('cv/upload');
}
}
In .htaccess I have:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
Also, for my wamp, I have enabled mod_rewrite module.
Can you please help me out with this? I want to use url http://localhost/laravel-first-app/public/cv instead of http://localhost/laravel-first-app/public/index.php/cv
Please help.
go to the project folder, open terminal and then run php artisan serve it will start localhost:8000 or similar like that then simply go to https://localhost:8000/articles for your required page
I looked carefully to the application structure, I figured out what was the problem.
Now, I resolved the issue and every thing is working fine.
In the Controller, CvController, I had sent a directory CV, and path name was also CV, so it was behaving weirdly.
If you want detailed solution for this, let me know.
Thanks anyways.
I am trying to use RESTful controller. Here is my Route.php:
Route::resource('test', 'TestController');
Route::get('/', function()
{
return View::make('hello');
});
Here is my TestController.php
<?php
class TestController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return View::make('test.home');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
My app route is localhost/Test/public/ and it shows "You have arrived" message. But when I tried localhost/Test/public/test It gives me "Symfony\Component\HttpKernel\Exception\NotFoundHttpException"
Here is my log:
[2014-05-11 14:29:59] production.ERROR: NotFoundHttpException Route: `http://localhost/Test/public/test` [] []
[2014-05-11 14:29:59] production.ERROR: exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' in C:\wamp\www\test\bootstrap\compiled.php:5289
Stack trace:
#0 C:\wamp\www\test\bootstrap\compiled.php(4663): Illuminate\Routing\RouteCollection->match(Object(Illuminate\Http\Request))
#1 C:\wamp\www\test\bootstrap\compiled.php(4651): Illuminate\Routing\Router->findRoute(Object(Illuminate\Http\Request))
#2 C:\wamp\www\test\bootstrap\compiled.php(4643): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#3 C:\wamp\www\test\bootstrap\compiled.php(698): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#4 C:\wamp\www\test\bootstrap\compiled.php(679): Illuminate\Foundation\Application->dispatch(Object(Illuminate\Http\Request))
#5 C:\wamp\www\test\bootstrap\compiled.php(1136): Illuminate\Foundation\Application->handle(Object(Illuminate\Http\Request), 1, true)
#6 C:\wamp\www\test\bootstrap\compiled.php(7218): Illuminate\Http\FrameGuard->handle(Object(Illuminate\Http\Request), 1, true)
#7 C:\wamp\www\test\bootstrap\compiled.php(7815): Illuminate\Session\Middleware->handle(Object(Illuminate\Http\Request), 1, true)
#8 C:\wamp\www\test\bootstrap\compiled.php(7762): Illuminate\Cookie\Queue->handle(Object(Illuminate\Http\Request), 1, true)
#9 C:\wamp\www\test\bootstrap\compiled.php(10768): Illuminate\Cookie\Guard->handle(Object(Illuminate\Http\Request), 1, true)
#10 C:\wamp\www\test\bootstrap\compiled.php(640): Stack\StackedHttpKernel->handle(Object(Illuminate\Http\Request))
#11 C:\wamp\www\test\public\index.php(49): Illuminate\Foundation\Application->run()
#12 {main} [] []
I know this question has been asked many times. I had gone through many relevant threads but just can not figure out the solution.
A NotFoundHttpException exception in Laravel always means that it was not able to find a router for a particular URL. And in your case this is probably a problem in your web server configuration, virtual host (site) configuratio, or .htaccess configuration.
Your public/.htaccess should look like this:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
As you can see there is a condition in the first line IfModule mod_rewrite.c, so if you don`t have mode_rewrite installed or enabled, all rewrite rules will fail and this
localhost/Test/public/
Will work fine, but not this:
localhost/Test/public/test
In other hand, this one should work too, because this is its raw form:
localhost/Test/public/index.php/test
Because Laravel needs it to be rewritten to work.
And note that you should not be using /public, your URLs should look like this:
localhost/Test/
This is another clue that your virtual host's document root is not properly configured or not pointing to /var/www/Test/public, or whatever path your application is in.
All this assuming you are using Apache 2.
I had this case. I checked all of my codes and my solution was:
php artisan route:cache
Because I forgot to clear the route cache.
Before my web.php was like below
Route::group(['prefix' => 'admin', 'middleware' => ['role:admin']], function() {
Route::resource('roles','Admin\RoleController');
Route::resource('users','Admin\UserController');
});
In url enterd
http://127.0.0.1:8000/admin/roles
and get the same error. The solution was :
Route::group(['middleware' => ['role:admin']], function() {
Route::resource('roles','Admin\RoleController');
Route::resource('users','Admin\UserController');
});
Remove 'prefix' => 'admin', as both Controllers are located in Admin folder
like Arjan Koole says, I had a similar error
using:
Route::get('/performance/{$submit_type}/{$send_selected}/{$date_a}/{$date_b}', 'PerformanceController#calc');
instead of
Route::get('/performance/{submit_type}/{send_selected}/{date_a}/{date_b}', 'PerformanceController#calc');
So be aware when you use {$stuff}
In my scenario, the problem was I've used an extra prefix slash like:
Route::get('/plans', 'PayPalController#getPlansList')->name('paypal.plans');
instead of:
Route::get('plans', 'PayPalController#getPlansList')->name('paypal.plans');
I have found another situation where this error can occur, and that one has nothing todo with rewrites, for once. It's a very nasty typo :)
I had:
Route::get('replicas/item/{id}/{?stub}', ['uses' => 'ProductReplicasController#productview', 'as' => 'database.replicas.productview']);
see the {?stub}, that caused this error with me, it needs to be {stub?} off course. But if you're new to Laravel (like me), that is very easy to miss and could take quite some time to figure out. :)
another thing to check is your document root,
mine was:
www/var
and should be:
www/var/mysite/public
Another reason why I hate web development
I was getting the same error exception while one project was working but another project with same .htaccess file on same localhost was not working. Turns out since my project directory has capital letter in it, URL also should be capital for routing to work. localhost/minorweb/public/account was not working but localhost/minorWeb/public/account with W capital was working.
so, if nothing seems to solve the problem, check your URL is matched with project directory with case.
Put this in root .htaccess file
The below code do three things :
Remove index.php from url .
Remove public from url .
fix your problem .
Note : RewriteRule ^ index.php [L] this code solve your problem my problem was not added [L] after index.php
RewriteEngine On
<IfModule mod_rewrite.c>
#Session timeout
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
Options +FollowSymlinks
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]
RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
In my case I put {$id} instead {id} in the Route
in my case:
I had to use POST method but i was using the GET! method in web.php Rout
I am new into Codeigniter programming. I started CI by simply editing my default controller welcome. I added a function into the controller which is called on clicking a submit button. I havent done any modification in the default framework or in the config files. But upon clicking the submit button, the application returns a 404 response.
Not Found
The requested URL /login/welcome/main was not found on this server.
Apache/2.2.14 (Ubuntu) Server at localhost Port 80
The main function is what I wrote in the welcome controller. Can anyone please tell me what is wrong. My Codeigniter version is 2.1.0.
I re installed Apache and PHP. But no use still same. The code from controller and the welcome page below.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(E_ALL);
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('login_page');
//$this->load->view('phpinfo');
}
public function main()
{
$this->load->view('phpinfo');
}
And the welcome page is
<div id="container">
<h1>Ignitor</h1>
<div id="body">
<code>Please Login to continue. </code>
<div id="login_form">
<?php echo form_open(base_url().'welcome/main');?>
<ul>
<li>
<label>Username </label>
<?php echo form_input(array('id' => 'username', 'name' => 'Username'));?>
</li>
<li>
<label>Password </label>
<?php echo form_password(array('id' => 'password', 'name' => 'Password'));?>
</li>
<li> <?php echo form_submit(array('id'=>'submit'),'Let me in' )?></li>
</ul>
<?php echo form_close();?>
*/
Dude..
class Welcome extends CI_Controller {
public function index()
{
// echo 'Index';
$this->load->view('welcome');
// Then save the file in your application/views/welcome.php
// http://yours.com/index.php/welcome
// Or http://yours.com/welcome <-- With htaccess
}
public function main()
{
// echo 'Index';
$this->load->view('main');
// Then save the file in your application/views/main.php
// http://yours.com/index.php/welcome/main
// Or http://yours.com/welcome/main <-- With htaccess
}
}
By default, the index.php file will be included in your URL
You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
Have you setup the .htaccess file? It should be something like:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
You are skipping index.php in the URL which means you are expecting a .htaccess file to be routing the request to CodeIgniters main index.php.
Use the URL /login/index.php/welcome/main to check if your .htaccess file is faulty or not present. If you renamed or moved the directory it is in to 'login' you may have forgotten to update that.
Your .htaccess in the 'login' directory should look something like -
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /login/index.php/$1 [L]
If it was finding the main index.php and the error was due to a view/model/controller naming issue you would get an 404 from CodeIgniter, not Apache.
Did you correctly name your welcomepage view file? In other words, your controller is asking to for login_page_view.php (or at least I believe that's the default filename convention) to be in the views folder based on the line of code:
$this->load->view('login_page');