I have a login form. I want when user login success, my controller will select data of this user and share to all view.
I read laravel docs. [This][1] advises me to use the "View::share('key', 'value');"
in boot method of AppServiceProvider, but i dont know how to call it in my controller
my controller:
if( Auth::attempt(['mssv' => $username,'password' =>$password])) {
$user=SinhVien::where('mssv',$username)->first();
//i want to share $user to all view in here
$success = new MessageBag(['successlogin' => 'Login Success]);
return redirect()->back()->withErrors($success);
}
else {
$errors = new MessageBag(['errorlogin' => 'Login Fail']);
return redirect()->back()->withErrors($errors);
}
and in all view blade, I use:
{{$user->name}}
Please help!
[1]: https://laravel.com/docs/5.7/views#sharing-data-with-all-views
In your blades you would then have access to the key from the View::share('key', 'value'); you put in the AppServiceProvider.
So if the key is user, in your blades you just use the $user variable.
<!-- Stored in resources/views/layouts/app.blade.php -->
<html>
<head>
<title>App Name - #yield('title')</title>
</head>
<body>
<header>
<div>
#if(auth()->user())
{{ auth()->user()->name }}
#else
<button>login</button>
#endif
<div>
</header>
<div class="container">
#yield('content')
</div>
</body>
EDIT :
{{ auth()->user->name }} corrected -> {{ auth()->user()->name }}
Related
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'));
}
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
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")!!}
I don't want that users can access images from simply using a URL like http://laravel.dev/123.jpg. Therefore I store all images in the storage directory, instead of storing them in the public folder.
With a controller like this
public function show($id) {
$img = storage_path('my_images/123.jpg');
return response()->download($img, null, [], null);
}
the image is correctly displayed by Laravel 5, although it is stored outside from the public folder.
Great up to this point ... but I want to use Blade and surround the image with some more details. Therefore my controller looks like this
public function show($id) {
$picture = Picture::find($id);
$img = storage_path('my_images/123.jpg');
return view('pictures.show', array('picture' => $picture, 'img' => $img));
}
and the view like this
<!DOCTYPE html>
<html>
<head>
<title>Picture {{ $picture->id }}</title>
</head>
<body>
<h1>Picture {{ $picture->id }}</h1>
<ul>
<li>Name: {{ $picture->name }}</li>
<li>Description: {{ $picture->description }}</li>
</ul>
<img src="{{ $image }}">
</body>
</html>
which obviously does not work, because the location of the image is not publicly accessible (which ist the intention).
What do I have to use instead of <img src="{{ $image }}"> to make this work?
Make the src attribute to call the URL of your first controller, this will work for you.
In other words, let's say, you have a route called image.show with that code.
public function show($id) {
$img = storage_path('my_images/123.jpg');
return response()->download($img, null, [], null);
}
So in your blade:
<img src={{route("image.show",$img_object)}}">
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);