Tomasz
Tomasz

Reputation: 1408

How to return view with anchor in Laravel 5?

In my controller

return view('pages.index', compact('errors'));

and it works ok but I don't know how to return view to anchor.

return view('pages.index#contact', compact('errors'));

not works. Error like this appear.

InvalidArgumentException in FileViewFinder.php line 137:
View [pages.index#contact] not found.

Upvotes: 3

Views: 2462

Answers (3)

raaaahman
raaaahman

Reputation: 158

I know this question is quite old, but in Laravel 8 I have been able to do it with named routes:

Route::get('/', function() {
    return view('home');
})->name('home');

Then in a blade template:

<a href="{{route('home')}}#portfolio">Home</a>

Upvotes: 0

Aksh
Aksh

Reputation: 654

For That purpose You can Use Url() Helper function and route should be defined because view() helper function just maps the first argument and fetch that file having .blade extension. In your case it is fetching index.blade.php from page folder. if you will use fragment #container with it then it won't be able to find that file. so in that case use Url() helper function.

So you can do:

URL::to('/pages/index?contact');

In routes.blade.php

$route->get("/pages/index?contact","PageController")->with('errors',$errors);

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

You can use some JS. Pass anchor variable first:

$anchor = 'contact';
return view('pages.index', compact('errors', 'anchor'));

Then use hidden or something else to pass data to JS:

@if (isset($anchor))
    <input type="hidden" name="anchor" value="{{ $anchor }}">
@endif

And finally use JS to move the page:

$(function () {
    if ( $( "[name='anchor']" ).length ) {
        window.location = '#' + $( "[name='anchor']" ).val();
    }
};

It's just an example to give you an idea.

Upvotes: 6

Related Questions