15
votes

I am new in laravel 5 . I am working on larvel page security and i have to prevent open some page or Url but when i use {{ Redirect::to('/dashboard') }} in view it is not working .

Please help me to find a way to use Redirect / Url in laravel view (Blade template)

I have already tried :-

  1. {{ url('/dashboard') }}
  2. {{ Redirect::to('/dashboard') }}

Code :-

@if(Auth::user()->role_id == 1)
{{ 'Page' }}
@else 
{{ Redirect::to('/dashboard') }}
@endif
6
have you checked laravel's redirect function - Prashant G Patil
Yes but they are only for controller .. - Aman Kumar
Can you please show some more clarity with code? exactly need to confirm if it reached till the code or not. Because there is no error mentioned, you are getting any error ? or just happens nothing? - Ajit Hogade
I have added my code please check - Aman Kumar
@AmanKumar check this stackoverflow.com/questions/34089905/… the same logic applies to check is a user has role_id == 1 - Nicolas

6 Answers

27
votes

Use a JavaScript redirect instead:

@if(Auth::user()->role_id == 1)
  {{ 'Page' }}
@else 
  <script>window.location = "/dashboard";</script>
@endif
9
votes
@if(your conditions)
    @php
        header("Location: " . URL::to('/'), true, 302);
        exit();
    @endphp
@endif
6
votes

Your question is hard to understand, but I suppose you want to redirect the user on the view after check if he is login. I have bad news for you, logic goes on the Controller not on Views.

That means you need to check if the user is login on the Controller and after that you redirect to the proper view, on Laravel the most common way to do it is to create a Middleware that checks if the user is login and then apply the correct logic.

You have a lot of ways to do it, but at first you need to understand how it works, you can check it on the Laravel Authentication docs.

5
votes

Use route path with Javascript redirect:

  @if(Auth::user()->role_id == 1)
      {{ 'Page' }}
   @else 
      <script>window.location = "{{ route('admin.list') }}";</script>
      <?php exit; ?>
   @endif
4
votes
@if(put_your_condition_here)
  {{session(['must_login'=>'must_login'])}};//if you want to display flash message
 window.location.href = "{{url('put your route here')}}";
@endif  
2
votes

I was able to create this redirect using Javascript

@if(Auth::user()->role_id == 1)
  {{ 'Page' }}
@else 
  <script>
    window.location = "/dashboard";
  </script>
@endif