简体   繁体   中英

Laravel Controller method not found for homepage

I am aware that my code is slightly wrong (hence my post!). I am wanting my 'home' view to be displayed when a visitor accesses the '/' part of the website.

Currently, the view works when a user accesses the '/home' part of the website. I am currently pulling my hair out on how to do this!

Route.php:

Route::controller('/', 'HomeController');
Route::controller('users', 'UsersController');
Route::get('events/{id}/{slug}', 'EventsController@show');
Route::controller('events', 'EventsController');

HomeController.php:

<?php

class HomeController extends BaseController {

    protected $layout = "layouts.main";

    public function getHome(){

        $events = myApp\Event::where('date','>=', DB::raw('CURDATE()'))->first();
        $this->layout->content = View::make('home', array('events' => $events));
    }
}

Home.blade.php:

<div class="col-md-4">
    <h2>Next Event</h2>
    <h3>{{$events->title}}</h3>
    <p>Presented by {{ $events->consultant()->first()->title }} {{ $events->consultant()->first()->surname }}</p>
    <b><p>{{ date("j F Y", strtotime($events->date)) }} from {{ date("g:ia", strtotime($events->start_time)) }}</p></b>
    <a class="btn btn-success" href="{{ URL::to('events/' . $events->slug) }}">Book your place now.</a>
</div>

I have managed to get the view working with the '/' directory by using this within my routes.php:

Route::get('/', function(){
    return View::make('home');
});

However, I am presented with the error:

Undefined variable: events (View:/Users/Sites/gp/app/views/home.blade.php).

It's as if, the HomeController isn't passing the 'events' array into the view, by just changing the route?! Any help/remedy/explanation would be hugely appreciated.

That's how Laravel RESTful controllers works, but you can create a new route for / , before your other routes, pointing to that action:

Route::controller('users', 'UsersController');
Route::get('events/{id}/{slug}', 'EventsController@show');
Route::controller('events', 'EventsController');

Route::get('/', 'HomeController@getHome');
Route::controller('/', 'HomeController');

EDIT

You have to understand that the Laravel Routing System tries to resolve a route as fast as it can, so if it finds a route that fits the current URI, it will use that route and forget about all the others. An example:

Route::get('/{variable}' 'Controller@action');

This is pretty generic route and can be resolved to anything, even

http://your-site.dev/events

So, if you add that route before this one:

Route::get('events/{id}/{slug}', 'EventsController@show');

Your events route will never be hit. That's why your most generic route have to be the last one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM