How do I define variables in Laravel using Routes - laravel

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'));
}

Related

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

Ask about sub view in laravel blade template

I'm want to ask about sub view in laravel blade the specific situation is as follows.
a view of pages
I want when click to component 1(2), The contents of the child blade file in #section('sub-view') will be rendered in the #yield('sub-view'). and this is the code of the parent blade file.
parent blade file
#extends('layouts.default')
#section('content')
<div class="row">
<div class="col-4">
<ul class="list-unstyled">
<li>
Component 1
</li>
<li>
Component 2
</li>
</ul>
</div>
<div class="col-8">
#yield('sub-view')
</div>
</div>
#endsection
And the code of child blade file.
child blade file
#section('sub-view')
<p>This is component 1</p>
#endsection
and my route file
Route file
Route::group(['prefix' => 'projects'], function () {
Route::get('', function () {
return View::make('pages.project.projects');
});
Route::get('comp1', function () {
return view('pages.project.comp1');
});
Route::get('comp2', function () {
return view('pages.project.comp2');
});
});
Can someone just help me solve this problem?
Thank
I think you need to add an
#extends('parent') // or whatever your parent view is called
to your child view file.
For more info:
https://laravel.com/docs/5.7/blade#template-inheritance

Route [/createhotel] not defined. laravel 5.4

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")!!}

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?

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