redirect.php 2.45 KB
Newer Older
Taylor Otwell committed
1
<?php namespace Laravel;
2

Taylor Otwell committed
3
class Redirect extends Response {
4 5

	/**
6
	 * Create a redirect response.
7
	 *
8 9 10 11 12 13 14 15 16 17 18
	 * <code>
	 *		// Create a redirect response to a location within the application
	 *		return Redirect::to('user/profile');
	 *
	 *		// Create a redirect with a 301 status code
	 *		return Redirect::to('user/profile', 301);
	 *
	 *		// Create a redirect response to a location outside of the application
	 *		return Redirect::to('http://google.com');
	 * </code>
	 *
19 20 21
	 * @param  string    $url
	 * @param  int       $status
	 * @param  bool      $https
22
	 * @return Redirect
23
	 */
24
	public static function to($url, $status = 302, $https = false)
25
	{
26
		return static::make('', $status)->header('Location', URL::to($url, $https));
27 28 29
	}

	/**
30 31 32 33 34 35
	 * Create a redirect response to a HTTPS URL.
	 *
	 * @param  string    $url
	 * @param  int       $status
	 * @return Response
	 */
36
	public static function to_secure($url, $status = 302)
37
	{
38
		return static::to($url, $status, true);
39 40 41
	}

	/**
42 43
	 * Add an item to the session flash data.
	 *
44 45
	 * This is useful for passing status messages or other temporary data to the next request.
	 *
46 47 48 49 50
	 * <code>
	 *		// Create a redirect response and flash something to the session
	 *		return Redirect::to('user/profile')->with('message', 'Welcome Back!');
	 * </code>
	 *
51 52
	 * @param  string          $key
	 * @param  mixed           $value
53 54
	 * @return Response
	 */
55
	public function with($key, $value)
56
	{
57
		if (Config::get('session.driver') == '')
58
		{
Phill Sparks committed
59
			throw new \LogicException('A session driver must be set before setting flash data.');
60 61
		}

62
		IoC::core('session')->flash($key, $value);
63

64
		return $this;
65 66 67
	}

	/**
68
	 * Magic Method to handle creation of redirects to named routes.
69 70 71 72 73 74 75 76
	 *
	 * <code>
	 *		// Create a redirect response to the "profile" named route
	 *		return Redirect::to_profile();
	 *
	 *		// Create a redirect response to a named route using HTTPS
	 *		return Redirect::to_secure_profile();
	 * </code>
77
	 */
78
	public static function __callStatic($method, $parameters)
79
	{
80
		$status = (isset($parameters[1])) ? $parameters[1] : 302;
Taylor Otwell committed
81 82
		
		$parameters = (isset($parameters[0])) ? $parameters[0] : array();
83

84 85
		if (strpos($method, 'to_secure_') === 0)
		{
86
			return static::to(URL::to_route(substr($method, 10), $parameters, true), $status);
87 88 89 90
		}

		if (strpos($method, 'to_') === 0)
		{
91
			return static::to(URL::to_route(substr($method, 3), $parameters), $status);
92 93
		}

Phill Sparks committed
94
		throw new \BadMethodCallException("Method [$method] is not defined on the Redirect class.");
95 96
	}

97
}