Laravel 4 displaying flash message doesn't work - php

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

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?

My alert doesn't show up in laravel 5

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

Authenticate user Laravel

hi guys i have an simple application with laravel and i try to add a user Authentication to my app , this is my route.php file :
Route::model('task', 'Task');
Route::get('/login', 'HomeController#ShowLogin');
Route::post('/login', 'HomeController#doLogin');
Route::get('/logout' , 'HomeController#doLogout');
Route::group(array('before'=>'auth'), function(){
Route::get('/', 'TasksController#home');
Route::get('/create', 'TasksController#create');
Route::get('/edit/{task}', 'TasksController#edit');
Route::post('/edit', 'TasksController#doEdit');
Route::post('/create' , 'TasksController#saveCreate');
Route::get('/delete/{task}' , 'TasksController#delete');
Route::post('/delete', 'TasksController#doDelete');
Route::get('/task/{id}' , 'TasksController#show')->where('id', '\d+');
});
this is my HomeController.php ;
class HomeController extends BaseController {
public function showLogin()
{
return View::make('login');
}
public function doLogin()
{
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
dd(Auth::attempt($userdata));
if(Auth::attempt($userdata))
{
return Redirect::to('/');
}
else
{
return Redirect::to('login');
}
}
public function doLogout()
{
Auth::logout();
return Redirect::to('login');
}
}
and this is my login.blade.php file :
#extends('layout')
#section('content')
<section class="header section-padding">
<div class="background"> </div>
<div class="container">
<div class="header-text">
<h1>Learning Laravel: The Easiest Way</h1>
<p>
Showing a single task <br/> using route parameter!
</p>
</div>
</div>
</section>
<div class="container">
<section class="section-padding">
<div class="jumbotron text-center">
<h1>
Login
</h1>
<P>
{{ $errors->first('username') }}
{{ $errors->first('password') }}
</P>
{{ Form::open(['url' => '/login', 'class' => 'form']) }}
<div class="form-group">
{{ Form ::label('username', 'Username:') }}
{{ Form::text('username')}}
</div>
<div class="form-group">
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</div>
<div class="form-group">
{{ Form::submit('Login', ['class' => 'btn btn-primary']) }}
</div>
{{ Form::close() }}
</div>
</section>
</div>
#stop
when i input any username and password i got no error and i never login , and i redirect to login page and dd() always return bool(false), can any one help that , and explain more about Authentication in Laravel , Thank U :)
Edit
and this is my model/User.php and i dont add any code to this :
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
i create my user table manually
Auth::attempt($userdata) method will hash the password in $userdata array and check that hashed password with the database value,
so you need hashed passwords in the database,
to verify that,
please change the password in the database to $2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy , and use a for the password field in the form
$2y$10$3S3yDwfkwwLghedu4AoaTe//61QTaNC0ycTdp8hLfHtQS4XrgBPQy is the laravel hashed password for a.

Laravel Getting Error with Validations

I am trying to Get Validation Errors on index.blade.php having issues:
When I fill both the fields then it goes well if i just put an Echo or Return in getLogin Controller.
When I just fill one field and it works good if i just put and echo or Return but not giving validation errors, with Validation Errors it only shows, "Something went Wrong"
Code for index.blade.php
<section class="mainWrap">
<div class="headingfirst"><img src="{{ URL::asset('css/des.png') }}" width="78"></div>
<div class="sedhead">Hey User!!!! Try to Login</div>
<div class="againtext">Sign In To Your Account</div>
<article class="FormContainer">
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
<img class="profile-img" src="{{ URL::asset('css/avatar_2x.png')}}">
{{ Form::open(array('class'=> 'SetMe')) }}
{{ Form::text('email',null, array('placeholder'=>'Email','class'=>'insi')) }}
{{ Form::password('password',array('placeholder'=>'Password','class'=>'dnsi')) }}
{{ Form::submit('Sign In', array('class'=>'SignIn')) }}
{{ Form::close() }}
</article>
</section>
Code for AuthController.php
<?php
class AuthController extends Controller{
public function GetLogin() {
return View::make('layouts.index');
}
public function LogInfo() {
$rules = array('email' => 'required','password' =>'required');
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::route('login')
->withErrors($validator);
}
else{
}
}
}
Code for Routes.php
Route::get('login', array('uses'=>'AuthController#GetLogin' ));
Route::post('login', array('uses'=>'AuthController#LogInfo'));
even when i put the Auth Code it don't show anything except "Something goes wrong". but while working with just Echos it works properly
In validation failed statement,
You need to use return Redirect::to('login') instead of return Redirect::route('login').
In index.blade.php, it should be like -
#foreach($errors->all() as $error)
<div class="errors">{{ $error }} </div>
#endforeach
instead of
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
Also here is my suggestion. if you are currently developing an application using laravel, it is the best to enable debug. Open laravel/app/config/app.php and make sure 'debug' => 'true'. It will help you see what is detailed error messages with stack traces.

Laravel Auth Redirect to Previous Page

I am attempting to create a single page like application with Laravel 4. When the user arrives at the site, they should be prompted to log in. Once the user logs in, the view (not the URL) will switch and the user will be able to see information as if they are authenticated.
My HTML (if authroized should show "Auth" in h1, if not, it shows login form)
<div class="container">
#if(Auth::check())
<h1>Auth</h1>
#else
{{ Form::open(array('url'=>'login', 'method'=>'post')) }}
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'example#test.com')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array('class'=>'form-control')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ Form::submit('Log In', array('class'=>'btn btn-primary pull-right')) }}
</div>
</div>
{{ Form::close() }}
#endif
</div>
Controller
class SiteController extends BaseController {
public function getIndex()
{
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
return Redirect::route('index');
}
}
}
My user model is the default that ships with Laravel 4. As of now, I am passing the Auth::attempt and getting the return Redirect::route('index');, but the #if(Auth::check()) doesn't seem to be firing. Instead it continues to show me the log in form. Am I doing something wrong here?
I don't see anything wrong here, but you need to be sure what's happening, it looks like your authenticated session is not sticking, but to be sure you could:
<?php
class SiteController extends BaseController {
public function getIndex()
{
Log::info('index - authed: '. Auth::check() ? 'yes' : 'no');
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
Log::info('postLogin - attempt successful');
return Redirect::route('index');
}
Log::info('postLogin - error on attempt');
}
}
And then check your logs:
php artisan tail

Categories