[Laravel] Laravel Redirect

[Laravel] Laravel Redirect updated_at: 2024-03-15 11:13

Redirect

redirect 는 반드시 get만 동작합니다.

redirect

특정 url 로 보냄

return redirect('/login');
return redirect()->to('/here');

Back

이전 파일로 움직일 때 사용

return redirect()->back()

withwithInput

입력값을 함께 보낼때 사용

return redirect()->back()->withInput();
return redirect()->back()->withInput()->withErrors($validator->errors()); 

특정 정보를 제외하고 보낼때 사용

redirect()->back()->withErrors($validator->errors())->withInput($request->except('password'));

withInput으로 보낼 경우 blade에서는 old로 받아서 처리

<input type="text" name="title" value="{{old('title')}}">

withErrors

주로 validation 이후 에러 발생시 처리
아래 with는 세션값을 별도로 정의해 주나 withErrors의 경우는 errors라는 세션에 collection 형태로 값들이 들어간다.

return redirect()->back()->withErrors($validator->errors()); 

첫번째 에러값을 보냄

return redirect()->back()->withErrors($validator->errors()->first());

특정 키로 보내기

return back()->withErrors(['email' => 'Email is invalid!']);

blade에서 에러 처리

아래와 같이 특정 name에 대해서 validation에러가 발생할 경우 @error에 특정 name을 명시하고 $message를 호출하면 된다.

  • view

특정 key 값 존재 확인 후 처리

@error('nameField')
  {{$message}}
@enderror
@if ($errors->has('email'))
  {{ $errors->first('email') }}
@endif

모든 에러 표시

@if ($errors->any())
  @foreach ($errors->all() as $error)
      <li>{{ $error }}</li>
  @endforeach
@endif

첫번째 에러만 표시

@if ($errors->any())
  {{$errors->first()}}
@endif

사용자 정의하여 처리하기

return redirect()->to('/here')->withErrors(['message1'=>'this is first message']);
  • view
{{session('errors')->first('message1');}}

with

정의된 이름으로 session값을 입력하여 리다이렉트 시킴

redirect()->back()->with('error', 'Failed to find that resource');
  • view
{{ session()->get('error') }}
@if ( session('error'))
  {{ session('error') }}
@endif
return redirect('dashboard')->with('status', 'Profile updated!');
  • view
@if (session('status'))
  {{ session('status') }}
@endif

intended

intended 는 특정페이지에 접속할때(로그인이 필요한 경우) 로그인 페이지로 이동하고 다시 원래 원하던 페이지인 특정페이지로 이동시킨다.

return redirect()->intended('/home);

/vendor/laravel/framework/src/Illuminate/Routing/Redirector.php 를 보면 더 이해가 쉬울 것이다.

public function intended($default = '/', $status = 302, $headers = [], $secure = null)
{
  $path = $this->session->pull('url.intended', $default);
  return $this->to($path, $status, $headers, $secure);
}

위를 보면 url.intended에서 값을 가져오고 만약 없을 경우 default로 제시된 값을 가져와서 redirect하는 것이다.
url.intended session에 값을 넣어 주어야 하는데 그 기능이 \Redirect::setIntendedUrl($request->getUri()); 이다.
이부분을 login 페이지 전인 곳에 넣어 주면 된다.
혹은 Session::put('url.intended', URL::previous()); 처럼 사용하여도 무방한다.

Route

정의된 라우트로 전송

return redirect()->route('login');
return redirect()->route('profile', [$user]);

Action

return redirect()->action('HomeController@index');
return redirect()->action(
  'UserController@profile', ['id' => 1]
);

Away

외부링크로 리다이렉트 할때 사용

return redirect()->away('https://www.google.com');

301 vs 302

redirect를 할 때 HTTP Response Status Code로 301, 302 를 주로 사용합니다.
301은 영구적으로 redirect 할때 302는 일시적인 리다이렉트 할때 입니다.
302의 경우는 특정 페이지 접근시 조건(회원의 권한이나 컨텐츠 권한등등)에 따라 분기시 주로 사용하고
301는 http를 https로 변경하거나 특정 url이 다른 url로 변경되었거나 할때 사용합니다.
라라벨에서는 redirect를 할 때 기본적으로 302를 사용하는데 만약 동일 콘텐츠인데 url이 다를 경우(http -> https, onstory.com -> www.onstory.com) 에는 SEO상 301 로 지정하는 것이 유리합니다.

return redirect()->route('events.show', $slug); // 302

return redirect(route('events.show', $slug), 301); // 301
return redirect('/bar', 301); 
return Redirect::to($id, 301); 
Route::permanentRedirect('/here', '/there'); // permanentRedirect 를 사용시 301
Route::redirect('/here', '/there', 301);
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글