Route [/createhotel] not defined. laravel 5.4 - laravel

This is my index view page.
#extends('layouts.app')
<!DOCTYPE html>
<html lang="en">
<head>
<link href="css/hotel.css" rel="stylesheet" type="text/css"/>
</head>
<body>
#section('content')
<h2>Hotels</h2>
<div class="container-fluid sug-1">
<div class="ui_column is-12 h1 ui_header sug-1head">{{ $data[0]->city}}
</div>
<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
#for ($i = 0; $i < 4; $i++)
<div class= "img__wrap">
<form method="get" action="/hotel/viewpost.blade.php">
<img class = "img__img" src={{asset($data[$i]->image)}} alt="Logo" style="width:90%;height:90%" >
<p class = "img__description"> {{$data[$i]->name}} <br> {{$data[$i]->rating}}<br> {{$data[$i]->price}}</p>
</form>
</div>
#endfor
<input class="sug1btn" type=Button id="allsugbtn" onclick="findHotels();" value="See all"/>
</div>
#endsection
</body>
</html>
This is controller for my index:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HotelController extends Controller
{
public function index()
{
$hotelData['data'] = \DB::table('hotels')->get();
if(count($hotelData) > 0)
{
return view("hotel.index",$hotelData);
}
else
{
return view("hotel.index");
}
}
}
I created a route from my index to viewpost i.e. following code:
#extends('layouts.app')
<!DOCTYPE html>
<html lang="en">
<head>
<link href="css/hotel.css" rel="stylesheet" type="text/css"/>
</head>
<body>
#section('content')
<div class="container-fluid sug-1">
<div class="ui_column is-12 h1 ui_header sug-1head">
</div>
<div style="display:flex; flex-direction: row; justify-content: left; align-items: left">
<div class="card">
<img src={{asset($data->image)}} alt="Image" style="width:100%">
<div class="container">
<h4><b>{{$data->name}}</b></h4>
<p>Rating: {{$data->rating}}<br>Price: {{$data->price}}</p>
</div>
</div>
<button href="{{ route('/createhotel') }}" type="button" class="btn btn-default">Left</button>
</div>
<h2>Reviews</h2>
#foreach ($reviews as $review)
<p>{{ $review->user_name }}<br>{{ $review->description }}</p>
<br><br><br>
#endforeach
#endsection
</body>
</html>
This is HotelPostController for my viewpost and createhotel:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HotelPostsController extends Controller
{
public function show($hotelviewid)
{
$imagedata['data'] = \DB::table('hotels')->select('id','image','name','city','rating','price' )->where('id', $hotelviewid)->first();
$reviewdata['reviews'] = \DB::table('hotel_reviews')->where('hotel_id', $hotelviewid)->get();
return view("hotel.viewpost",$imagedata,$reviewdata);
}
public function createhotel()
{
return view("hotel.createhotel");
}
}
This is web.php routes file:
Route::get('/', 'HotelController#index');
Route::get('/hotel', 'HotelController#index');
Route::get('/hotel/viewpost/{hotelviewid}', 'HotelPostsController#show');
Route::get('travelapp.me/hotel/viewpost/createhotel, 'HotelPostsController#createhotel');
The problem I am facing is that in views folder I have created a sub folder by name of hotel, it has 3 files index, viewpost and createhotel. the frst page is index and when a user clicks on some post it opens in viewpost. Now from there I want to create a button that goes to the third page i.e. creathotel. I have created a funtion in controller also added routes but it gives the error of undefined routes.

Change
Route::get('travelapp.me/hotel/viewpost/createhotel, 'HotelPostsController#createhotel');
to
Route::get('/hotel/viewpost/createhotel, 'HotelPostsController#createhotel');
And your button to go to create page:
Create Hotel
The method url() will give you the full URL automatically. You just need to create URL from root (/) and you dont have to attache full domain.
You can do like this (Just an example)
Route::get('/hotel-create, 'HotelPostsController#createhotel');
and button to go to that page
Create Hotel
Now in this example, When you click on Create Hotel link, this will gonna call the method createhotel() of HotelPostsController controller.
Update:
Problem
In your controller you are not passing any data to the view
public function createhotel()
{
return view("hotel.createhotel");
}
So how can you access the variable called $data on
<img src={{asset($data->image)}} alt="Image" style="width:100%">
Solution: (Pass your data to template)
public function createhotel()
{
$imagedata['data'] = \DB::table('hotels')->select('id','image','name','city','rating','price' )->where('id', $hotelviewid)->first();
$reviewdata['reviews'] = \DB::table('hotel_reviews')->where('hotel_id', $hotelviewid)->get();
return view("hotel.createhotel",$imagedata,$reviewdata);
}

The route() helper method accepts the name as the parameter, not the actual route.
route('create') is what you want. To use the url, url('/hotel/create').

Route::get('/hotel/create', 'HotelReviewController#create')->name('create');
change it to
Route::get('/hotel/create', 'HotelReviewController#create')->name('createhotel');
it will work i hope. you are using named route read here about routing.
https://laravel.com/docs/5.6/routing#named-routes

in your index action value filled by a view blade page and it seems wrong
<form method="get" action="/hotel/viewpost.blade.php">
and in viewpost you need to change {{ route("/create") }} to {!! route("create")!!}

Related

How do I define variables in Laravel using Routes

I'm getting errors when trying to put variables in my Laravel code. I know you're supposed to define the variables in the routes,but I'm getting nowhere. I'm trying to build a cms website.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<div class="row align-items-center mr-5">
#foreach($abouts as $about)
<div class="col-lg-6 pl-lg-5 ">
<h3 class=" font-weight-bold">About Us</h3>
<p class="text-justify pt-3 mr-5">Test.</p>
<p class="text-justify pt-3 mr-5">Test.</p>
</div>
</div>
#endforeach
</ul>
</body>
</html>
This is the code that I used in the web.php files
Route::get('/about', [App\Http\Controllers\AboutController::class, 'about'])->name('about');
This is the code that I used in my AboutController files
public function about()
{
return view('/about');
}
As you want to access $abouts variable in your Blade template you should pass it when rendering the about template.
It should be like this
public function about()
{
// Here the variable which contain the data
$abouts = []; // And pass some data
// Here you pass all data for the $about variable to template which is rendered
return view('/about', compact('abouts'));
}
in the about controller you need to bind to the view the data
use App\Models\About;
public function about()
{
$abouts = About::all();
return view('/about',compact('abouts'));
}

Including a sign up form in the master layout

I would like to put my sign up form in my footer of my Laravel app so that it appears on all the pages on footer. I have no idea regarding this. Would appreciate basic sample codes for the controller and the form.
CONTACT FORM
<input type="text" name="email" placeholder="Email" value="{{old('email') }}">
<span class="errors">{{ $errors->first('email') }} </span>
#csrf
<span class="subscribe-button"><input type="submit" value="subscribe" /></span>
</form>
</div>
SubscribeController.php
<?php
namespace App\Http\Controllers;
use App\Mail\SubscribeMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail
class SubscribeController extends Controller
{
public function create()
{
return view('contact.subscribe');
}
public function store()
{
$data = request()->validate([
'email' => 'required|email',
]);
Mail::to('test#test.com')->send(new SubscribeMail($data));
return redirect('');
}
The subscribe.blade is inside my footer using #include('contact.subscribe')
You are on the right track, keep up! However, you have some issues inside the store function:
public function store(Request $request)
{
$data = $request()->validate([
'email' => 'required|email',
]);
Mail::to('test#test.com')->send(new SubscribeMail($data));
return redirect()->route('home');
}
Anyway, if you are looking to include a sign-up form that appears on all of the pages you should define a layout that has a basic header, footer, and a sign-up form.
<!-- Stored in resources/views/layouts/app.blade.php -->
<html>
<head>
<title>App Name - #yield('title')</title>
</head>
<body>
<div class="container">
#yield('content')
</div>
<footer>
<p>Amazing footer with the sign-up form</p>
<form>
<!-- Inputs -->
</form>
</footer>
</body>
</html>
After that, you can create any number of pages, which should extend your main layout.
<!-- Stored in resources/pages/home.blade.php -->
#extends('layouts.app')
#section('title', 'Home Page')
#section('content')
<p>This is my Home page.</p>
#endsection
Read more about it on official Laravel documentation - https://laravel.com/docs/6.x/blade#defining-a-layout

How to use Ajax to update RenderBody()

I am trying to work with ajax in order to update only a partial view and not the whole view. In the following example I want to refresh the page-content section.
this is my layout.html.
<body>
<div id="container" class="effect">
#Html.Partial("_head")
<div class="boxed">
<section id="content-container">
#if (ViewData["Errors"] != null)
{
<div class="panel" style="background-color:white;">
<div class="panel-heading">
<h3 class="panel-title">
Page title
</h3>
</div>
</div>
}
<div id="page-content" class="container">
#RenderBody()
</div>
</section>
</div>
</div>
</body>
Partial view _head contains the menu with href links for example:
<a id="a1" href="">Menu Item 1</a>
In layout I am trying to use the following:
<script>
$(document).ready(function () {
$("#a1").click(function () {
A1();
});
function A1( ) {
$.ajax({
url: '#Url.Action("PartialViewMethodFromController", "HomeController")',
success: function (response) {
$('#page-content').html(response);
}
});
}
});
</script>
And my HomeController
public ActionResult PartialViewMethodFromController()
{
var model = service.GetAll();
return PartialView("PartialViewMethodFromController", model);
}
It kinda works - the partialview is refreshing for a moment and the partialview is show correctly and then the whole page goes on and refreshes.
Am I missing something crucial here?

Angular-devise 401 unauthorized error on landing page

I am building an app ROR that uses Devise for authentication and the angular-devise gem to link my angularJS front-end to rails.
When I come to the landing page of the app though the console is showing an error which I understand to be devise trying to sign in and having no username or password for that. My question is: Why is it trying to sign in?
I admit my limited understanding of how Devise and Angular-devise work. So I am not being able to debug this error. On top of that I m having the error twice, which I understand to be devise trying to sign in twice. I still don't know where these calls are being made to improve the code.
navCtrl.js
angular.module('theNotesApp')
.controller('navCtrl', ['$scope', 'Auth', '$state', 'notesFactory', 'Flash', function($scope, Auth, $state, notesService, Flash) {
$scope.signedIn = Auth.isAuthenticated;
$scope.logout = Auth.logout;
$scope.successAlert = function() {
var message = '<strong> Well done!</strong> You successfully read this important alert message.';
Flash.create('success', message, 'custom-class');
// First argument (success) is the type of the flash alert
// Second argument (message) is the message displays in the flash alert
// You can inclide html as message (not just text)
// Third argument (custom-class) is the custom class for the perticular flash alert
};
// When the controller loads the function below is executed and the currentUser returned promise is set as
//the value of $scope.user
Auth.currentUser().then(function(user) {
$scope.user = user;
});
$scope.$on('devise:new-registration', function(event, user){
$scope.user = user;
});
$scope.$on('devise:login', function (event, user){
$scope.user = user;
});
$scope.$on('devise:logout', function (event, user){
$scope.user = {};
$state.go('welcome');
$scope.clear();
});
}])
authCtrl.js
angular.module('theNotesApp')
.controller('authCtrl',['$scope', '$state', 'Auth', function($scope, $state, Auth) {
$scope.login = function() {
Auth.login($scope.user).then(function () {
$state.go('home');
});
};
$scope.register = function() {
Auth.register($scope.user).then(function () {
$state.go('home');
});
};
}])
application_controller.rb
![class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
respond_to :json
before_action :configure_permitted_parameters, if: :devise_controller?
def angular
render 'layouts/application'
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << :username
end
end][3]
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>The Notes App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<!--jquerytag must be on top as it's required for bootstrap.min.js-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!--javascript plugins -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
<body ng-app="theNotesApp">
<nav class="navbar navbar-default" ng-controller="navCtrl" ng-show="signedIn()" >
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#/home">The Notes App</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#/home" >+ New Note</a></li>
<li class="active" ng-hide="signedIn()">Register <span class="sr-only">(current)</span></li>
<li ng-hide="signedIn()">Login</li>
<li ng-show="signedIn()">{{user.email}}</li>
<li ng-show="signedIn()"><a ng-click="logout()">Logout</a></li>
</ul>
</div>
</div>
</nav>
<ui-view></ui-view>
</body>
</html>
welcome.html
<div class="intro-header fadein">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="intro-message" style="color: black">
<h1>The Notes App</h1>
<h3>Access your notes anywhere, anytime!</h3>
<hr class="intro-divider">
<ul class="list-inline intro-social-buttons">
<li>
<i class="fa fa-twitter fa-fw"></i> <span class="network-name">Login</span>
</li>
<li>
<i class="fa fa-github fa-fw"></i> <span class="network-name">register</span>
</li>
</ul>
</div>
</div>
<div class="col-lg-12" >
</div>
</div>
</div>
<!-- /.container -->
</div>
In navCtrl.js you have:
Auth.currentUser().then(function(user) {
$scope.user = user;
});
This is responsible for one of the sign-in attempt.
I don't know where the other attempt is from. I would advise you to check for a similar call by running grep -r Auth\.currentUser app in you Rails root folder.
If my guess is right, signedIn() function will be fire up "sign_in.json" call.
If yes then it is due to ng-show="signedIn()" / ng-hide="signedIn()" that you have in application.html.erb.
Ng-show & ng-hide will be evaluated when the page is parsed.

Laravel:Passing variable from controller to view

chatcontroller.php function returns variable to view:
public function getChat()
{
$message = chat_messages::all();
return View::make('home',compact($message));
}
this is my route:
Route::get('/getChat', array('as' => 'getChat','uses' => 'ChatController#getChat'));
this is my home.blade.php:
#extends('layouts.main')
#section('content')
<div class="container">
<h2>Welcome to Home Page!</h2>
<p> <a href="{{ URL::to('/logout') }}" > Logout </a></p>
<h1>Hello <span id="username">{{ Auth::user()->username }} </span>!</h1>
<div id="chat_window">
</div>
<input type="text" name="chat" class="typer" id="text" autofocus="true" onblur="notTyping()">
</div>
<ul>
#foreach($message as $msg)
<li>
{{ $msg['sender_username']," says: ",$msg['message'],"<br/>" }}
</li>
#endforeach
</ul>
<script src="{{ asset('js/jquery-2.1.3.min.js') }}"></script>
<script src="{{ asset('js/chat.js') }}"></script>
#stop
I am trying to send result returned by select query to view from controller.
when I do this from homecontroller.php then it works fine.
if I try to pass from controller which I have defined it gives error message as:Undefined variable.
I have used the extends \BaseController do i need to do anything else to access my controller variable from view.
please suggest some tutorial if possible for same.
Verify the route to be sure it uses the new controller:
Route::get('user/profile', array('uses' => 'MyDefinedController#showProfile'));
First of all check your routes, as Matei Mihai says.
There are two different ways to pass data into your view;
$items = Item::all();
// Option 1
return View::make('item.index', compact('items'));
// Option 2
return View::make('item.index')->with('items', $items); // same code as below
// Option 3
View::share('item.index', compact('items'));
return View::make('item.index);
You can also do this:
$this->data['items'] = Item::all();
return View::make('item.index', $this->data);

Resources