Laravel not redirecting to route - laravel

I'm trying to validate some data from a form and redirect the user to the page with any errors if any. My code doesn't redirect to any route. The routing for all of my routes works correctly. I echoed the input with Input::all() and it does have the user input. The validator works as well. I'm not sure exactly what's preventing the Redirect::route from working
public function postPurchase()
{
$validator = Validator::make(Input::all(), array(
'condition' => 'required',
'memory' => 'required',
'color' => 'required',
'accessories' => 'required',
'shipping' => 'required'
));
// $input = Input::all();
// dd($input);
if ($validator->fails()) {
// echo "string";
return Redirect::route('home');
} else {
echo "this succedded";
}
//Get prices, item id, etc and send user to checkout page
// echo "Get prices, item id, etc and send user to checkout page";
}
This is the code that precede the postPurchase method:
public function getPurchase()
{
return View::make('general.purchase');
}
public function getCheckout()
{
return View::make('general.checkout');
}
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
if (Input::get('buy')) {
$this->postPurchase();
}
elseif (Input::get('cart')) {
$this->postAddCart();
}
}

You call the function - but you dont 'return' the Redirect that is given back to you.
Change
if (Input::get('buy')) {
$this->postPurchase();
}
to
if (Input::get('buy')) {
return $this->postPurchase();
}

Try updating this
if (Input::get('buy')) {
return $this->postPurchase();
} elseif (Input::get('cart')) {
return $this->postAddCart();
}
and
if ($validator->fails()) {
// echo "string";
return Redirect::to('home');
} else {
echo "this succedded";
}
also don't forget to define it on route file

Change you postPurchaseCheck() method to return what is returned by $this->postPurchase() like this. Because you are calling the postPurchase() method internally but post is happening on postPurchaseCheck() method so redirect has to be returned by the method that handle POST request
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
if (Input::get('buy')) {
return $this->postPurchase();
}
elseif (Input::get('cart')) {
return $this->postAddCart();
}
}

Related

Laravel Form Request unique field validation on update

I have to make Form Request and have a unique rule on the title. How to ignore unique validation for updating id?
These are my rules when I try to get an id passed from the controller.
public function rules()
{
$id = $this->request->get('id') ? ',.' $this->request->get('id') : '';
$rules = [
'title' => 'required|min:3|unique:parent_categories',
];
if ($this->getMethod() == 'PUT' || $this->getMethod() == 'PATCH') {
$rules += ['title' => 'required|min:3|unique:parent_categories,title' . $id];
}
return $rules;
}
This is my controller where I am trying to update content with id.
public function update(ParentCategoryRequest $request, $id)
{
DB::beginTransaction();
try {
$parentCategory = ParentCategory::update($id, $request->all());
DB::commit();
return $this->success('Parent category updated successfully', new ParentCategoryResource($parentCategory), 201);
} catch (Exception $e) {
DB::rollBack();
return $this->error($e->getMessage(), $e->getCode());
}
}
I am getting...
undefined variable $id on ParentCategoryRequest

How To Create Conditional for Unique Validation (UPDATE/PATCH) on Form Request

I'm trying to get my controller cleaner by moving 'validation request' into a form request called 'BookRequest'.
The problem is on the update process, I try to create a condition to check, if it PATCH or POST with the following codes
MyRequest.php
public function rules()
{
// Check Create or Update
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->get('id');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->get('id');
}
else
{
$a_rules = 'required|string|size:6|unique:books,column2';
$b_rules = 'sometimes|string|size:10|unique:books,column3';
}
return [
'column1' => 'required|string|max:100',
'column2' => $a_rules,
'column3' => $b_rules,
'column4' => 'required|date',
'column5' => 'required|in:foo,bar',
'column6' => 'required',
'column7' => 'required',
'column8' => 'required',
];
}
.$this->get('id') it failed, the form still treat the unique on the update.
Controller#update
public function update($id, BookRequest $request)
{
$book = Book::findOrFail($id);
$input = $request->all();
$book->update($request->all());
return view('dashboards.book');
}
Controller#edit
public function edit($id)
{
$book = Book::findOrFail($id);
return view('dashboards.edit', compact('book'));
}
Controller#create
public function create()
{
return view('dashboards.create');
}
Controller#store
public function store(BookRequest $request)
{
$input = $request->all();
$book = Book::create($input);
return redirect('dashboards/book/index');
}
I try the alternative .$book->id, and it throw me an ErrorException Undefined variable: book
Any suggestion? I'm using Laravel 5.2 by the way
You are using book as your route parameter but trying to get with id. try this-
if ($this->method() == 'PATCH')
{
$a_rules = 'required|string|size:6|unique:books,column2,' .$this->route()->parameter('book');
$b_rules = 'sometimes|string|size:10|unique:books,column3,' .$this->route()->parameter('book');
}
Hope it helps :)

Laravel route : any slug takes all the requests

I have a route something like this. The $slug is a variable that is matched to the slugs stored in the database to add the pages dynamically to the website.
#slug variable for different values of page slug....
Route::get('/{slug?}', array(
'as' => 'page',
'uses' => 'AbcController#renderPage'
));
However, now I wish to add an admin side of the website and want routes to be prefixed with media-manager.
My problem is, whenever I make a call to another route in the file, the above mentioned route takes the request call and calls the renderPage method every time, no matter wherever the request is coming from.
This is my middleware where I check for whether request is coming from a URL like 'media-manager/*', if so I don't want to check for the language of the website and redirect it to the media-manager's page.
private $openRoute = ['media-manager/login', 'media-manager/postLogin', 'media-manager/media'];
public function handle($request, Closure $next)
{
foreach ($this->openRoute as $route) {
if ($request->is($route)) {
return $next($request);
}
}
// Make sure current locale exists.
$lang = $request->segment(1);
if(!isValidLang($lang)) {
$lang = getDefaultLang();
$segments = $request->segments();
array_unshift($segments, $lang);
$newUrl = implode('/', $segments);
if (array_key_exists('QUERY_STRING', $_SERVER))
$newUrl .= '?'.$_SERVER['QUERY_STRING'];
return $this->redirector->to($newUrl);
}
setLang($lang);
return $next($request);
}
This is the renderPage method where every time the request is being redirected, no matter what.
public function renderPage($slug = '')
{
if ($slug == 'login') {
return view ('site.login');
}
$page = Page::getBySlug($slug);
if(empty($page)){
return URL::to ('/');
}
if($slug == ''){//home page
$testimonial = DB::table('testimonial')->where('lang','=',$this->lang)->get();
$client_logo = DB::table('client_logo')->get();
return View::make('index', compact('data','page', 'testimonial', 'client_logo'));
}elseif($slug == 'services'){
return View::make('services', compact('page'));
}elseif($slug == 'portfolio'){
$categories = PortfolioCategory::getAll();
$portfolio = Portfolio::getAll();
return View::make('portfolio', compact('page', 'categories', 'portfolio'));
}elseif($slug == 'oshara'){
return View::make('oshara', compact('page'));
}elseif($slug == 'blog'){
$limit = 8;
$pageNum = 1;
$offset = ($pageNum-1)*$limit;
$totalPosts = BlogPost::totalPosts();
$totalPages = ceil($totalPosts/$limit);
$posts = BlogPost::getAll($offset, $limit);
$blog_posts = View::make('partials.blog_posts', compact('posts','pageNum','totalPages'));
return View::make('blog', compact('page', 'blog_posts', 'pageNum', 'totalPages'));
}elseif($slug == 'contact'){
$budgets = Budget::getAll();
return View::make('contact', compact('page', 'budgets'));
}
}
This is postLogin method in the controller that I want to call after user clicks on Login button on login page.
public function postLogin($request) {
# code...
//$request = $this->request;
$this->validate($request, [
'email1' => 'required|email',
'password' => 'required|string'
]);
if($user = User::whereEmail($request->email1)->first() ) {
if(Hash::check($request['password'], $user->getAttributes()['password'])) {
if(!$user->getAttributes()['is_active']) {
return redirect('/media-manager/login')->withErrors('Your Account is not Activated Yet!');
} else if($user->getAttributes()['is_deleted']) {
return redirect('/media-manager/login')->withErrors('Your Account is Banned!');
} else {
# Success
$cookie = Cookie::make('user_id', $user->getAttributes()['id'], 864000);
//echo "hello";
return view('site.media')->with('message', 'You have Successfully Logged In!')->withCookie($cookie);
}
} else {
return redirect('/media-manager/login')->withErrors('Your Login Information is Wrong!');
}
} else {
return redirect('/media-manager/login')->withErrors('Your Login Information is Wrong!');
}
}
Can any one please suggest me some way so that I can disable renderPage method on every call and have my normal routing perform perfectly.
In Laravel the first matching route is used. So I would guess you have your slug route defined above the others (at least above the media-manager ones), right?
So a simple solution would be to just put the slug route definition at the end of your routing file.
Another approach would be utilize conditions for the route. For more information you can read this or leave a comment!
Hope that helps!

Restriction for not allowing same email and password in the database for my signup form

i want to make a restriction in my signup form which the user cant signup with the already exists email and password..
in my controller:
i already make a rules or callback
array(
'field' => 'txt_email',
'label' => 'Email',
'rules' => 'required|valid_email|callback_check_if_valid_email|trim',
),
check_if_valid:
public function check_if_valid_email()
{
$where = array('email' =>$this->input->post('txt_email'),'password' =>$this->input->post('txt_password'));
$this->load->model('database_model');
if ($user = $this->database_model->validate_user('user', $where))
{
foreach ($user as $row) {
$checkemail = $row->email;
$checkpassword = $row->password;
}
if ($checkemail == $this->input->post('txt_email')){
$this->form_validation->set_message('check_if_valid_email', 'Email already existed!');
return false;
}
else
{
if ($checkpassword = $this->input->post('txt_password'))
{
$this->form_validation->set_message('check_if_valid_email', 'Email already exists!');
return false;
}
else
{
return true;
}
}
}
}
in my model:
public function validate_user($table, $where)
{
$this->db->where($where);
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
CodeIgniter's Form Validation library comes with the rule you're looking for, called: is_unique
http://www.codeigniter.com/userguide3/libraries/form_validation.html#rule-reference
Your validation rules will look like this;
required|valid_email|is_unique[users.email]|trim
All you have to set it the table and column you want to be unique (users.email).
Hope this helps.

laravel auth and session not persisting

The laravel session and auth I use have some problem in server, but working really fine in localhost . I will show.
Route
Route::get('/signin', 'PageController#signin');
Route::get('/signup', 'PageController#signup');
Route::get('/terms', 'PageController#terms');
Route::resource('/', 'PageController');
Route::controller('user', 'UserController');
PageController
public function index() {
if (Auth::check()) {
return View::make('user.index');
} else {
return View::make('landing');
}
}
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Redirect::to('/');
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
Auth::check() fails in pagecontoller even after login succeds. But if I change the code to
UserController
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
} else {
$data['success'] = false;
}
} else {
$data['success'] = false;
}
return $data;
}
I get the index page and if I click the link of the home I get the landing page not the index page.
I guess I clarify my problem, I have gone through may solution replied earlier in same manner question nothing working.
I don't think its the server problem because another laravel application is working fine in same server.
Please help.
Your query seems to be incomplete, from what i understand you are able to get the index page after passing the authentication check only once, and that is by using this method:
public function postLogin() {
$data = array();
$secured = ['user_email' => $_POST['email'], 'password' => $_POST['password']];
if (Auth::attempt($secured, isset($_POST['remember']))) {
if (Auth::user()->user_status == 1 ) {
return Return View::make(user.index);
}
else {
$data['success'] = false;
}
}
else {
$data['success'] = false;
}
return $data;
}
try using a different browser to make sure there is no cookie storage restrictions in the client side and check the app/config/session.php file and see if you have configured the HTTPS Only Cookies according to your needs.
and just on an additional note this line "return Return View::make(user.index);" looks vague.

Resources