Lynal's avatar
Level 1

Route always redirect to '/'

Hello all !

I'm having a strange issue. When I call the route "/article/next/{lastId}/{search?}", it redirects me to the index method ("/") instead of the "getNextArticles" method.

Can you tell me what I did wrong?

Here is my route.php :

Route::get('/', ['as' => 'home', 'uses' => 'MainController@index']);
Route::get('/back/{id}', ['as' => 'home.back', 'uses' => 'MainController@getBackHomeWithArticle']);
Route::get('/article/{id}/{name}', ['as' => 'article.get', 'uses' => 'MainController@getArticle']);


Route::get('/article/next/{lastId}/{search?}', ['as' => 'article.next', 'MainController@getNextArticles']);
Route::get('/article/category/{categoryId}', 'MainController@getArticleByCategory');
Route::get('/article/autocomplete/{search?}', 'MainController@getArticlesListAutocomplete');

Route::get('/contact', 'MainController@contact');
Route::post('/contact', 'MainController@contact');

Thank you !

0 likes
5 replies
zachleigh's avatar

Please show your MainController file. Also be sure to wrap code in three backticks.

```

// code

```

Lynal's avatar
Level 1

Oh that's how you do it :) ! I didn't know :).

I switched the route position of '/next/{id}/{search?}' and '/article/{id}/{name}' and now I have an error :

[2017-03-19 20:29:23] local.ERROR: exception 'ReflectionException' with message 'Function () does not exist' in /opt/workspace/franck/bootstrap/cache/compiled.php:8722

Here is what I changed :

 */
Route::get('/', ['as' => 'home', 'uses' => 'MainController@index']);
Route::get('/back/{id}', ['as' => 'home.back', 'uses' => 'MainController@getBackHomeWithArticle']);
Route::get('/next/{id}/{search?}', ['as' => 'article.next', 'MainController@getNextArticles']);
Route::get('/article/{id}/{name}', ['as' => 'article.get', 'uses' => 'MainController@getArticle']);


Route::get('/article/category/{categoryId}', 'MainController@getArticleByCategory');
Route::get('/article/autocomplete/{search?}', 'MainController@getArticlesListAutocomplete');

Route::get('/contact', 'MainController@contact');
Route::post('/contact', 'MainController@contact');

And here is the MainController :

<?php
namespace App\Http\Controllers;

use App\Article;
use App\ArticleType;
use App\Category;
use App\Configuration;
use Illuminate\Http\Request;
use App\Mail\VisitorContact;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MainController extends Controller
{
    const ARTICLE_SHOW_LIMIT = 100000;
    const ARTICLE_AUTOCOMPLETE_LIMIT = 10;

    public function __construct()
    {
        $config = Configuration::get();
        if (isset($config)) {
            foreach ($config as $conf) {
                $arrayConfig[$conf->name] = $conf->value;
            }
        }

        \View::share('config', $arrayConfig);
    }

    public function index(Request $request)
    {
        $search = $request->input('search', '');
        $categories = Category::whereNull('parent_category_id')
            ->orderBy('position')
            ->get();

        $orderedUne = $this->getUne();

        return view('home', ['search' => $search, 'categories' => $categories, 'une' => $orderedUne]);
    }

    public function getBackHomeWithArticle($id)
    {
        return redirect()->route('home')->with('backTo', $id);
    }

    /**
     * Action when a visitor sends a message
     */
    public function contact(Request $request)
    {
        if ($request->isMethod('post')) {
            $name = $request->input('name');
            $email = $request->input('email');
            $phone = $request->input('phone');
            $type = $request->input('type');
            $message = $request->input('message');

            $sendTo = '[email protected]';

            switch ($type) {
                case 'technique':
                    $sendTo = '[email protected]';
                    break;
                case 'professionnel':
                default:
                    $sendTo = '[email protected]';
                    break;
            }

            Mail::to($sendTo)
                ->send(new VisitorContact($email, $name, $phone, $message));
        }

        return redirect()->route('home')->with('status', 'Merci de nous avoir contactés et prenez soin du rock n\' roll !');
    }

    public function getArticleByCategory($categoryId = 0)
    {
        if ($categoryId > 0) {
            DB::enableQueryLog();
            $articles = Article
                ::join('article_category', 'articles.id', '=', 'article_category.article_id')
                ->join('categories', 'categories.id', '=', 'article_category.category_id')
                ->where('is_draft', 0)
                ->where('categories.id', '=', $categoryId)
                ->orWhere('categories.parent_category_id', '=', $categoryId)
                ->orderBy('articles.id', 'desc')
                ->distinct()
                ->get(array('articles.*'));
            Log::info(DB::getQueryLog());
        } else {
            $articles = Article
                ::where('is_draft', 0)
                ->orderBy('articles.id', 'desc')
                ->get();
        }

        if (isset($articles)) {
            foreach ($articles as $article) {
                if (empty($article->author)) {
                    $article->author = $article->originalAuthor->nickname;
                }
            }
        }

        return view('layouts.thumbnail-container', ['articles' => $articles]);
    }

    public function getArticlesListAutocomplete($search)
    {
        $result = array();

        if (!empty($search)) {
            $search = htmlentities($search);
            $articles = Article::with('type')
                ->where('is_draft', false)
                ->where('title', 'like', '%' . $search . '%')
                ->orderBy('id', 'desc')
                ->limit(MainController::ARTICLE_AUTOCOMPLETE_LIMIT)
                ->get();

            if (isset($articles)) {
                foreach ($articles as $article) {
                    $cutTitle = substr($article->title, 0, 40) . '...';
                    $result[] = array('label' => $cutTitle, 'url' => url('article', $article->id));
                }
            }
        }
        return response()->json(['autocomplete' => $result]);
    }

    public function getNextArticles($lastId = -1, $search = '')
    {
        if (intval($lastId) === -1 || $lastId == null) {
            $lastArticle = Article::get()->last();
            if (isset($lastArticle)) {
                $lastId = $lastArticle->id + 1;
            }
        }

        if (!empty($search)) {
            $search = htmlentities($search);
            $articles = Article::with('type')
                ->where('id', '<', $lastId)
                ->where('is_draft', false)
                ->where(function ($q) use ($search) {
                    $q->where('title', 'like', '%' . $search . '%')
                        ->orWhere('content', 'like', '%' . $search . '%')
                        ->orWhere('url_video', 'like', '%' . $search . '%')
                        ->orWhere('author', 'like', '%' . $search . '%');
                })
                ->orderBy('id', 'desc')
                ->limit(MainController::ARTICLE_SHOW_LIMIT)
                ->get();
        } else {
            $articles = Article::with('type')
                ->where('id', '<', $lastId)
                ->where('is_draft', false)
                ->orderBy('id', 'desc')
                ->limit(MainController::ARTICLE_SHOW_LIMIT)
                ->get();
        }

        if (isset($articles)) {
            foreach ($articles as $article) {
                if (empty($article->author)) {
                    $article->author = $article->originalAuthor->nickname;
                }
                $article->url_explicit = $this->cleanArticleTitle($article->title);
            }
        }

        return view('layouts.thumbnail-container', ['articles' => $articles]);
    }

    /**
     * Display a page with an article
     * @param $id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getArticle($id)
    {
        $article = Article::with('user')->where('is_draft', false)->find($id);

        if (isset($article)) {
            $orderedUne = $this->getUne();
            $categories = Category::whereNull('parent_category_id')
                ->orderBy('name')
                ->get();

            $articleType = ArticleType::where('id', $article->article_type_id)->first();

            $article->views_number++;
            $article->save();

            $article->type = $articleType->code;
            $article->url_cover = Storage::url($article->url_cover);
            $article->url_thumbnail = Storage::url($article->url_thumbnail);
            $article->url_twitter = str_replace('#', '', $article->title);

            if (!empty($article->user->avatar)) {
                $article->user->avatar = Storage::url($article->user->avatar);
            }

            if (!empty($article->originalAuthor->avatar)) {
                $article->originalAuthor->avatar = Storage::url($article->originalAuthor->avatar);
            }

            return view('home')->with(['search' => '', 'categories' => $categories, 'article' => $article, 'une' => $orderedUne]);
        } else {
            return redirect()->route('home')->with('status', 'L\'article n\'a pas été trouvé.');
        }
    }

    /**
     * Get Article to be displayed in an iframe
     * @param $id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getArticleForIframe($id)
    {
        $article = Article::
        where('is_draft', false)
            ->find($id);

        if (isset($article)) {
            $article->url_cover = Storage::url($article->url_cover);

            $articleType = ArticleType::
            where('id', $article->article_type_id)
                ->first();

            $article->type = $articleType->code;

            return view('article')->with(['article' => $article]);
        } else {
            return redirect()->route('home')->with('status', 'L\'article n\'a pas été trouvé.');
        }
    }


    /**
     * Get the une
     * @return array
     */
    private function getUne()
    {
        $orderedUne = array();
        $allUne = Article::where('une_position', '>', 0)
            ->whereNull('deleted_at')
            ->where('is_draft', 0)
            ->orderBy('une_position')
            ->get();

        if (isset($allUne)) {
            foreach ($allUne as $une) {
                if (empty($une->author)) {
                    $une->author = $une->originalAuthor->nickname;
                }
                $orderedUne[$une->une_position] = $une;
            }
        }
        return $orderedUne;
    }

    /**
     * Return a title without special chars
     * @param $title
     * @return string
     */
    private function cleanArticleTitle($title)
    {
        $trans = array(
            'à' => 'a',
            'â' => 'a',
            'ç' => 'c',
            "é" => "e",
            "è" => "e",
            "ê" => "e",
            'ô' => 'o',
            "'" => '',
            "," => "",
            "..." => "",
            '/' => '-',
            '\\' => '-',
            '?' => '',
            '&' => ''
        );

        $title = trim(strtolower($title));
        $title = strtr($title, $trans);

        $title = str_replace(' ', '-', $title);
        $title = str_replace(':', '', $title);
        $title = str_replace('#', '', $title);
        $title = str_replace('!', '', $title);
        $title = str_replace('---', '-', $title);
        $title = str_replace('--', '-', $title);


        if (substr($title, -1) == '-') {
            $title = substr($title, 0, -1);
        }

        if (substr($title, -1) == '.') {
            $title = substr($title, 0, -1);
        }

        return $title;
    }
}

Thank you, really :)

Lynal's avatar
Level 1

Oh, I forgot the 'uses' here :

Route::get('/next/{id}/{search?}', ['as' => 'article.next', 'MainController@getNextArticles']);
Snapey's avatar

I'm not quite following this thread, but you need to consider your routes carefully. They seem to be a bit of a mess.


Route::get('/article/{id}/{name}', ['as' => 'article.get', 'uses' => 'MainController@getArticle']);


Route::get('/article/category/{categoryId}', 'MainController@getArticleByCategory');


for instance, the second route above will never be executed because article/something/something will always be caught by the first. It will just assume 'category' is the id

Lynal's avatar
Level 1

Oh, you are absolutely right ! Thank you Snapey. There was indeed a problem with those routes.

They work better this way :

Route::get('/', ['as' => 'home', 'uses' => 'MainController@index']);
Route::get('/back/{id}', ['as' => 'home.back', 'uses' => 'MainController@getBackHomeWithArticle']);
Route::get('/article/{id}/{name?}', ['as' => 'article.get', 'uses' => 'MainController@getArticle']);
Route::get('/next/{id}/{search?}', ['as' => 'article.next', 'uses' =>'MainController@getNextArticles']);

Route::get('/category/{categoryId}', 'MainController@getArticleByCategory');
Route::get('/autocomplete/{search?}', 'MainController@getArticlesListAutocomplete');

Route::get('/contact', 'MainController@contact');
Route::post('/contact', 'MainController@contact');

Sorry I'm totally new to Laravel ! But thanks ;)

Please or to participate in this conversation.