I am new to Laravel and was following a tutorial (https://www.youtube.com/watch?v=Zz_R73eW3OU&list=PL09BB956FCFB5C5FD). I have just installed the latest version of Laravel and am going through the beginning stages of the tutorial. So far (installation, creating a migration) I was doing ok, but now I am stuck at the point of creating new routes.
I have created a controller in app/controllers:
<?php
class Slots_Controller extends Base_Controller{
public $restful = true;
public function get_index(){
return View::make( 'slots.index' );
}
}
As well as a very minimalist view in the file app/views/slots/index.php
<h1>Slots</h1>
My app/routes file looks like this :
Route::get('/', function()
{
return View::make('hello');
});
Route::get( '/public/slots', array(
'uses' => 'slots#index'
) );
I've searched a number of things on the web and here is how far I have come :
- i know ideally only the public dir should be in the htdocs, i will be doing that presumably at a further stage of the tutorial. so as of now, my laravel home page is at http://localhost:8888/my_directory.laravel/public/
- i have checked the apache mod-rewrite : it is on and it works well for codeIgniter
- i have checked that the .htaccess is as provided by laravel (and as suggested by different posts)
The weird thing is, if i change the routes for the home page like this :
Route::get('/', function()
{
return 'hello world';
// return View::make('hello');
});
Nothing changes, i.e. i still get the original welcome page. My understanding is this modification should have simply output "hello world" as the html for the home page.
So it seems that whatever I'm doing in routes.php has no effect whatsoever, as if I was modifying the wrong file or something.
I've spent the most part of an otherwise sunny afternoon on this, any help is much apreciated :)
Thanks,
Tepp
There are many things you are doing wrong here (The best way is to follow the tutorial on Laravel):
In your controller file you are mentioning "Base_Controller", are you sure you have such a file in your controllers directory? (According to my knowledge it should be BaseController)
The Route::get is not defined properly. There are many ways to define a route; however for your case it should be something like this:
Route::get('slots', array(
'uses' => 'Slots_Controller#get_index'
));
Hope this helps.
Related
I am following a tutorial to learn Laravel 8. I've created a simple view that contains 3 articles. Each article has a link to another html page. The exercise is to create URLs in web.php.ur
I have 2 views post.blade.php and posts.blade.php(the main one) , the other articles in html are contained in a posts folder in ressources.
Route::get('posts/{post}', function ($view) {
$post = file_get_contents(__DIR__ . "/../ressources/posts/{$view}.html");
return view('post', [
'post' => $post,
]);
});
This is the url: http://127.0.0.1:8000/posts/my-first-post
This the error I get:
file_get_contents(C:\xampp\htdocs\laravel2\laravel2\routes/../ressources/posts/my-first-post.html): Failed to open stream: No such file or directory
I don't understand what went wrong since I'm copying exactly what the tutorial is doing.
Start from here https://laracasts.com/series/laravel-8-from-scratch
You will have each nuts and bolts of laravel clear. This series is very precise to get you started in laravel.
In routes/web.php page
Route::get('/posts', [PostController::class, 'index']);
And in View page
Posts
First, i want to say that if your instructor really told you to write this
file_get_contents(__DIR__ . "/../ressources/posts/{$view}.html") , then he doesn't know anything about laravel and the MVC structure. stop following that.
This is the solution based on what i understood from your example:
so there is a html file named 'my-first-post.html' in your 'ressources/posts' directory. Rename it to 'my-first-post.blade.php'
in the post.blade.php file, just include that file using #include('posts.' . $post)
and change the controller to this:
Route::get('posts/{post}', function ($post) {
return view('post', [
'post' => $post,
]);
});
I have been working on this project of mine now for sometime and has no problem with routes until today.
I have even tried clearing cache and dump autoloading. Nothing seems to be working.
I tried to add a new route today and i got a 404 error. I have also use "get" and "any", all to no avail.
At first, I have tried creating several new routes and I'm still getting the same 404 error. Below is how a part of my web.php looks like.
Route::group(['middleware' => ['auth', 'role:teacher']], function () {
Route::any('/testing', 'PagesController#testing');
Route::resource('/attendance', 'AttendanceController');
Route::get('/teacher/dashboard', 'TeachersController#dashboard')->name('teacher.dashboard');
Route::resource('homework', 'HomeworkController');
Route::resource('/teacher/events', 'EventsController',['names' =>
'teacher.events']);
Route::any('/view_students', 'StudentsController#myStudents')->name('view.students');
Route::resource('results', 'CoursesResultController');
Route::get('/results/class_course/{id}', 'CoursesResultController#showCourseResult');
Route::post('/results/class_course/{id}', 'CoursesResultController#saveCourseResult');
});
EDIT: I have solved the issue. I had to delete the cache files in the bootstrap folder manually. Thanks, guys.
Replace your code with the following:
Route::resource() generates all the possible routes for you, hence should be kept as the last possible point.
Route::group(['middleware' => ['auth', 'role:teacher']], function () {
Route::any('/testing', 'PagesController#testing');
Route::resource('/attendance', 'AttendanceController');
Route::get('/teacher/dashboard', 'TeachersController#dashboard')->name('teacher.dashboard');
Route::resource('homework', 'HomeworkController');
Route::resource('/teacher/events', 'EventsController',['names' =>
'teacher.events']);
Route::any('/view_students', 'StudentsController#myStudents')->name('view.students');
/* changes over here
`Route::resource()` generates all the possible routes for you, hence should be kept as the last possible point.
*/
Route::get('/results/class_course/{id}', 'CoursesResultController#showCourseResult');
Route::post('/results/class_course/{id}', 'CoursesResultController#saveCourseResult');
Route::resource('results', 'CoursesResultController');
});
I am having troubles getting laravel to find a page when I route to it. My route is setup and being recognized as when I create link using URL::route('account-create') laravel will successfully parse that into '/account/create' as to where I want the link to go to. But upon clicking it I get a 404 error.
My route
Route::get('/account/create', array(
'as' => 'account-create',
'uses' => 'AccountController#getCreate'
));
My controller
class AccountController extends BaseController {
// view the create user form
public function getCreate()
{
//return View::make('account.create');
}
}
The create.blade.php is created and put inside an account folder under app/views. commenting or uncommenting makes no difference. The 404 remains.
I have also tried:
Route::get('/account/create', function()
{
return 'Hello World';
});
in my routes.php still the 404 remains
Is there some configuration I am missing?
After looking around some more I discovered I needed to enable rewrite_module on apache. Makes perfect sense really, how can laravel make clean urls if it cant rewrite the url. I knew it was going to be something simple to fix.
Thanks a lot for your replys
Does navigating to index.php/account/create work? If so, it is probably an error in your root-level .htaccess file, or in your VirtualHost settings in httpd.conf on your server. Post the contents of .htaccess from app/public.
I am a noob with laravel just picked it up today, what seems to be an easy task that looks lovable has caused a headache.
I am following a tutorial from Jeffery Way, and we seeded the database, the next step is to create a controller and get the resource. I generated the necessary files, then followed these basic steps.
The database table is 'players'
Step 1.
//Here is the index() function inside my PlayersController.php
class PlayersController extends \BaseController {
public function index()
{
return Player::all();
}
}
Step 2.
//Inside the app/models/ directory I create a file called Player.php
//Here is the code inside Player.php
class Player extends Eloquent {
protected $table = 'players' // I tried without the protect aswell
}
Step 3.
//Finially a route
Route::resource('players', 'PlayersController');
Route::get('/', function()
{
return View::make('hello');
});
For extra measure I also ran composer dump-autoload in the command line, inside the root directory of my laravel project.
Then now I wasnt told which directory the route would be in, since it's an index function I assumed it's inside the root, so I have tried several url's
http://localhost/basketball-app-framework/public/players
http://localhost/basketball-app-framework/players
This last one would obviously only work if I pointed localhost to the public directory, I did do that however, still a no go. I am confused as ever.
http://localhost/players
I have tried a bunch other url's but those only are the ones that make sense, and the ones I am pretty sure should be working.
It blows I have to do some digging to figure out this simple mistake I am sure I am making, but whatever it takes to understand why I cant fetch that data from my database.
Okay looks like it was a mod_rewrite, and AllowOverride All issue inside the http.conf file.
I figured out some better keywords that applied to my issued and came across this Laravel 4 simple route not working using mod_rewrite, and .htaccess
As of now the simple users route that the documentation provides works. http://localhost/basketball-app-framework/public/users returns Users!.
So its nice to have this figured out, I still feel confused though haha.
There will be several high profile links for customers to focus on, for example:
Contact Us # domain.com/home/contact
About the Service # domain.com/home/service
Pricing # domain.com/home/pricing
How It Works # domain.com/home/how_it_works
Stuff like that. I would like to hide the home controller from the URL so the customer only sees /contact/, not /home/contact/. Same with /pricing/ not /home/pricing/
I know I can setup a controller or a route for each special page, but they will look the same except for content I want to pull from the database, and I would rather keep my code DRY.
I setup the following routes:
Route::get('/about_us', 'home#about_us');
Route::get('/featured_locations', 'home#featured_locations');
Which work well, but I am afraid of SEO trouble if I have duplicate content on the link with the controller in the URL. ( I don't plan on using both, but I have been known to do dumber things.)
So then made routes like these:
Route::get('/about_us', 'home#about_us');
Route::get('/home/about_us', function()
{
return Redirect::to('/about_us', 301);
});
Route::get('/featured_locations', 'home#featured_locations');
Route::get('/home/featured_locations', function()
{
return Redirect::to('/featured_locations', 301);
});
And now I have a redirect. It feels dumb, but it appears to be working the way I want. If I load the page at my shorter URL, it loads my content. If I try to visit the longer URL I get redirected.
It is only for about 8 or 9 special links, so I can easily manage the routes, but I feel there must be a smart way to do it.
Is this even an PHP problem, or is this an .htaccess / web.config problem?
What hell have I created with this redirection scheme. How do smart people do it? I have been searching for two hours but I cannot find a term to describe what I am doing.
Is there something built into laravel 4 that handles this?
UPDATE:
Here is my attempt to implement one of the answers. This is NOT working and I don't know what I am doing wrong.
application/routes.php
Route::controller('home');
Route::controller('Home_Controller', '/');
(you can see the edit history if you really want to look at some broken code)
And now domain.com/AboutYou and domain.com/aboutUs are returning 404. But the domain.com/home/AboutYou and domain.com/home/aboutUs are still returning as they should.
FINAL EDIT
I copied an idea from the PongoCMS routes.php (which is based on Laravel 3) and I see they used filters to get any URI segment and try to create a CMS page.
See my answer below using route filters. This new way doesn't require that I register every special route (good) but does give up redirects to the canonical (bad)
Put this in routes.php:
Route::controller('HomeController', '/');
This is telling you HomeController to route to the root of the website. Then, from your HomeController you can access any of the functions from there. Just make sure you prefix it with the correct verb. And keep in mind that laravel follows PSR-0 and PSR-1 standards, so methods are camelCased. So you'll have something like:
domain.com/aboutUs
In the HomeController:
<?php
class HomeController extends BaseController
{
public function getAboutUs()
{
return View::make('home.aboutus');
}
}
I used routes.php and filters to do it. I copied the idea from the nice looking PongoCMS
https://github.com/redbaron76/PongoCMS-Laravel-cms-bundle/blob/master/routes.php
application/routes.php
// automatically route all the items in the home controller
Route::controller('home');
// this is my last route, so it is a catch all. filter it
Route::get('(.*)', array('as' => 'layouts.locations', 'before' => 'checkWithHome', function() {}));
Route::filter('checkWithHome', function()
{
// if the view isn't a route already, then see if it is a view on the
// home controller. If not, then 404
$response = Controller::call('home#' . URI::segment(1));
if ( ! $response )
{
//didn't find it
return Response::error('404');
}
else
{
return $response;
}
});
They main problem I see is that the filter basically loads all the successful pages twice. I didn't see a method in the documentation that would detect if a page exists. I could probably write a library to do it.
Of course, with this final version, if I did find something I can just dump it on the page and stop processing the route. This way I only load all the resources once.
applicaiton/controllers/home.php
public function get_aboutUs()
{
$this->view_data['page_title'] = 'About Us';
$this->view_data['page_content'] = 'About Us';
$this->layout->nest('content', 'home.simplepage', $this->view_data);
}
public function get_featured_locations()
{
$this->view_data['page_title'] = 'Featured Locations';
$this->view_data['page_content'] = 'Featured properties shown here in a pretty row';
$this->layout->nest('content', 'home.simplepage', $this->view_data);
}
public function get_AboutYou()
{
//works when I return a view as use a layout
return View::make('home.index');
}