My alert doesn't show up in laravel 5 - php

This is my alert.blade.php,
#if(Session::has('info'))
<div class="alert alert-info">{{ Session::get('info') }}</div>
#endif
And this is my welcome.blade.php,
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
#include('alert')
</body>
</html>
And, here's my routes.php,
Route::get('/', function () {
return view('welcome')->with('info','Hello World');
});
Any help will be really appreciated
Thanks in advance

return view('welcome')->with('info','Hello World');
This line returns the value of 'info' to the view and doesn't set it to the session. While your code:
#if(Session::has('info'))
<div class="alert alert-info">{{ Session::get('info') }}</div>
#endif
checks whether there exists a info variable in the session or not. So you need to change your view to:
#if(isset($info))
<div class="alert alert-info">{{ $info }}</div>
#endif
Which basically would check if the view has a variable called info and if it is true, it prints its value.

Using ->with() will result in a accesible variable inside your view.
You can choose to change it to:
#if (isset($info))
However there are some other cleaner ways to solve this.
You can use the function withErrors()
It would look like:
return view('yourView')->withErrors(['info' => 'Your message'])
And you can access it like:
#if ($errors->has('info'))
{{ $errors->first('info') }}
#endif

Related

All livewire functions not firing?

For some reason all of the livewire functions in my program have suddenly stopped working and I have no idea why. For example when I click the function to add friend it doesn't fire at all
This is what my app.blade.php part looks like
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap">
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
<script src="{{ asset('js/app.js') }}" defer></script>
#livewireStyles
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
#livewireScripts
</head>
<body class="font-sans antialiased">
This is what the AddFriend component class looks like:
class AddFriend extends Component
{
// public $user;
public function render()
{
$users = User::where('id', '!=', Auth::user()->id)->limit(14)->latest()->get();
$usersid=User::orderBy('created_at', 'desc')->pluck('id');
$attribute= Attribute::whereIn('user_id',$usersid)->get();
// dd($attribute);
return view('livewire.add-friend', compact('users'));
}
public function addToFriend($id)
{
try {
$user = Auth::user();
$recipient = User::find($id);
if (!$recipient) {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => 'User not found!']);
} else {
if ($user->befriend($recipient)) {
$this->dispatchBrowserEvent('alert', ['type' => 'success', 'message' => 'Request has been sent!']);
} else {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => 'Request has been failed!']);
}
}
} catch (\Exception $e) {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $e->getMessage()]);
}
}
This is what the all_users.blade.php looks like:
#extends('layouts.app')
#section('content')
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<article>
<div>
#livewire('add-friend')
</div>
This is the main part where the livewire function gets rendered(add-friend.blade.php):
<div>
#foreach ($users as $user)
<div render:poll="render">
<h3>{{$user->name}}</h3>
#if($user->attributes!=null)
<p>Grade is {{$user->attributes->GradeLevel}}</p>
<p>Age is {{$user->attributes->Age}}</p>
<p>Country is {{$user->attributes->Country}}</p>
#endif
#if(Auth::user()->hasSentFriendRequestTo($user))
<x-button type="submit" class="btn btn-red">Requested</x-button>
#elseif(Auth::user()->isFriendWith($user))
<x-button class="btn btn-green" type="submit" >Friends</x-button>
#else
<button wire:click="addToFriend({{ $user->id }})" class="btn btn-warning" type="button" > Add Friend</button>
#endif
</div>
#endforeach
</div>
I'm not sure what the issue as I'm being told that its to do with the div tags but they all surround the livewire tabs, so I'm not too sure , so it could be anything really. I don't know why all of the livewire functions have all stopped working and normal functions work fine
I can't say for sure, but I'm almost certain you're not supposed to be doing what you're doing in the render() method on your component.
In Livewire, render() is called on each component update, so you really don't want to use it to pass-in attributes like that. Instead, you should create properties on your Livewire component, and use $this->foo in your Blade template to access that data — refreshing state via component methods when necessary.
At the very least, querying your DB on each component render has some pretty bad implications where performance is concerned. You should move this logic into the mount() method on your component, and then store it in a public property for use in your Blade template. Also, where you're iterating in a #foreach, don't forget to include wire:key to help Livewire keep track of what needs updating.
Lastly, I'm not sure what render:poll="render" is in your Blade template. As far as I know, this isn't a Livewire attribute, and I can't find another reference of it in Laravel. Is this something custom or from another package?

Correct view output Laravel

That's my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Spieler;
class SpielerController extends Controller
{
public function getSpieler(Request $request){
$spielID = $request->get('spielID');
$spielerOutput = Spieler::where('spielPlanID', '=', $spielID)->get();
return view('spieler')->with('alleSpieler', $spielerOutput);
}
}
here you can see my view which I will trigger
#extends('app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{ $teamSpieler->note }}
#endforeach
#endif
#endsection
And here is my main index/app page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dateneingabe</title>
<link rel="stylesheet" href="/css/app.css">
<script src="{{ asset('/js/jquery-3.2.1.min.js') }}"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4">
#yield('contentSpiel')
</div>
<div class="col-lg-4">
#yield('contentSpieler')
</div>
</div>
</body>
</html>
When my controller is going to trigger i get back this in my console
<script src="http://localhost:8000/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h1>Spieler</h1> 2.5 Blasdasd
</div>
</div>
</body>
</html>
But I want only that {{ $teamSpieler->note }} should appear in my index/app page in the part #yield('contentSpieler'). What is wrong with my code? The correct value of note 2.5 is in the html console output but at the moment I don't know why there is no output on my index/app page?
if your master view file location is view->index->app.blade.php then
your view file should be like this
#extends('index.app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{$teamSpieler->note}}
#endforeach
#endif
#endsection
here your master view file location should be correct to extend it in your view file

Best way to output array from controller to view in laravel 5

I currently have this in my view to output data from an array that comes from my controller:
<!DOCTYPE html>
<html>
#foreach ($details as $detail)
<head>
<meta charset="utf-8">
<title>{{ $detail->name }}</title>
</head>
<body>
<h1>in view</h1>
{{ $detail->name }}
<br>
{{ $detail->street }}
<br>
{{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip }}
</body>
#endforeach
</html>
This is the function in my controller:
$details = DB::table('restaurants')->where('id', $restaurant_id)->get();
return view ('restaurant.detail')->with('details', $details);
My question is: is there a better way to do this? I tried using the blade syntax without the #foreach and didn't have any luck.
I don't want to output this multiple times, the only reason I have the foreach there is because it is the only way I could get it to output.
If this is how it is supposed to work, no worries, I am just not familiar enough yet with blade to know if there is a better way to output this.
Thank you!
You seem to be selecting something by id, so that's probably unique. When you do ->get() by default it will return a collection of results because it assumes there's always a chance that there's more than 1. When selecting by ID however you know if something exists by that id, there's only going to be 1 of it. You can change the code to:
$detail = DB::table('restaurants')->where('id', $restaurant_id)->first();
return view ('restaurant.detail')->with('detail', $detail);
<html>
<head>
<meta charset="utf-8">
<title>{{ $detail->name }}</title>
</head>
<body>
<h1>in view</h1>
{{ $detail->name }}
<br>
{{ $detail->street }}
<br>
{{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip }}
</body>
</html>
I highly recommend you look into Eloquent
Example of an eloquent model:
class Restaurant extends Model {} //The table name for model "Restaurant" is assumed to be restaurants
Then you can find a single restaurant:
$detail = Restaurant::find($restaurant_id);
Why do you want multiple title tags in your page ? It doesn't make any sense.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><!-- What do you want to show here ? --></title>
</head>
<body>
<h1>in view</h1>
#foreach ($details as $detail)
{{ $detail->name }}
<br>
{{ $detail->street }}
<br>
{{ $detail->city }}, {{ $detail->state }}. {{ $detail->zip}}
#endforeach
</body>
</html>
You can achieve this by below methods,
1. Use first() to retrieve single record like below,
// Controller Code
$detail = DB::table('restaurants')->where('id', $restaurant_id)->first();
<!-- View Code -->
<title>{{ $detail->name }}</title>
2. Use find() to retrieve single record by its primary key like below. It works similar to first() but it retrieves data by its primary key.
// Controller Code
$detail = DB::table('restaurants')->find($restaurant_id);
<!-- View Code -->
<title>{{ $detail->name }}</title>
3. You can use get() as you did in your question but you need to access it as array with 0th index. I assumed that your query will retrieve only one record. It won't fail even if it retrieves multiple records but you will only first record in your view.
// Controller Code
$details = DB::table('restaurants')->where('id', $restaurant_id)->get();
<!-- View Code -->
<title>{{ $detail[0]->name }}</title>
There could be some more approaches but I used only these approaches so far.

Laravel redirects to login on every page even after logging in

I'm having problems with Laravel since i removed Entrust.
Everything was working fine until i tried installing Entrust. I removed it because it kept saying the following message the same as this question Laravel cache store does not support tagging
Laravel cache store does not support tagging
I removed everything to do with Entrust and removed any changes I had to make but since then whenever I try to go to another page after logging in, it redirects back to the login page. I log back in and it redirects to the dashboard as it should but as soon as i go to another page, it redirects me back to login again.
Any ideas how to fix this?
UPDATE
I think i've narrowed down to the problem.
I created a new project and started again. I created the Auth, created a couple test controllers and views.
I logged in as normal and I got redirected to the Home contoller. I then went to another page and it loaded fine as it should. The views are using the default layout in views/layouts/app.blade.php. As soon as I change it to a custom layout the problem occurs again but is okay if i change it back to app.blade.php
Here is my new default.blade.php but i don't see why this doesn't work anymore
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>#yield('title')</title>
<link rel="icon" type="image/png" href="public/css/favicon-32x32.png" sizes="32x32">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css">
{{ HTML::style('css/bootstrap.css') }}
#if (!empty($styles))
#foreach($styles as $style)
{{ HTML::style($style . '.css') }}
#endforeach
#endif
{{ HTML::style('css/app.css') }}
{{ HTML::style('css/media.css') }}
</head>
<body class="{{ $body_class or '' }}">
<div class="wrapper">
#include('layouts.header')
#yield('content')
<div class="push"></div>
</div>
<div class="footer navbar-primary">
<div class="row">
<div class="col-xs-12">
<footer>
<p>© Copyright #php echo date('Y'); #endphp Axminster Tools & Machinery</p>
</footer>
</div>
</div>
</div>
<script>
window.website_url = '{{ URL::to('/') }}';
</script>
{{ HTML::script('assets/src/jquery/dist/jquery.min.js') }}
{{ HTML::script('assets/src/jquery-ui/jquery-ui.min.js') }}
{{ HTML::script('js/bootstrap.min.js') }}
{{ HTML::script('js/validate.js') }}
#if(isset($jsVars))
<script>
#foreach($jsVars as $key => $val)
var {{ $key }} = {{ $val }};
#endforeach
</script>
#endif
<script>
$(function() {
$("#searchform").submit(function(e) {
$("#searchform").attr("action", "/search/term/" + encodeURI($("#keywords").val()));
});
});
</script>
#if (!empty($scripts))
#foreach($scripts as $script)
{{ HTML::script($script . '.js') }}
#endforeach
#endif
</body>
</html>
I eventually found the problem.
After doing a new installation i tested the Auth and it worked. As soon as I copied across some of my template files I found the problem occurred again. After looking at the template layout files, I found I was using this for the logout link
Change password
I did this within the first few days of learning Laravel and it was never a problem before...don't know why.
I changed it to this and it all works as expected
Logout
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>

Laravel 4 displaying flash message doesn't work

I'm trying to display some flash messages, after I have successfully logged in. Can somebody help me understand why nothing is shown ?? Although I know the Session is true?`
This is my Sessions Controller:
class SessionsController extends \BaseController {
public function create()
{
return View::make('sessions.create');
}
public function store()
{
$attempt = Auth::attempt([
'email' => $input['email'],
'password' => $input['password']
]);
if($attempt) return Redirect::intended('/')->with('flash_message', 'You have been logged in!');
dd('problem');
}
public function destroy()
{
Auth::logout();
return Redirect::home();
}
}
And here is my view where the message should be displayed:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Yes</title>
</head>
<body>
<main>
#if(Session::get('flash_message'))
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#endif
<div class="container">
#yield('content')
</div>
</main>
</body>
</html>
I also tried this:
#if(Session::get('flash_message'))
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#else
<div class="flash">
{{ Session::get('flash_message') }}
</div>
#endif
But nothing get's displayed, just an empty nothingness, just like no message was parsed to the view.
Thanks for helping me out :)
In your store function, before if you should add:
Session::flash('flash_message', 'You have been logged in!');
This is used to store flash data in session. The with method won't work in a way you intend.
And then in view:
#if(Session::has('flash_message'))
{{ Session::get('flash_message') }}
#endif

Categories