Laravel 5.1 flash message handling - php

In Laravel 5.0 and 4.* there was this option to check if the Session had flash_messages:
Controller:
public function store(Request $request) {
Session::flash('flash_message', 'Success');
return redirect('somepage');
}
And then you could call this in your layout:
#if (Session::has('flash_message'))
<p>{{ Session::get('flash_message') }}</p>
#endif
This worked perfectly fine, however in Laravel 5.1 it changed. Now it's stored in the request variable. So, I changed it in the controller to:
public function store(Request $request) {
$request->session()->flash('flash_message', 'Success');
return redirect('somepage');
}
And I call this in the layout:
#if($request->session()->has('flash_message'))
<p>{{ $request->session()->get('flash_message') }}</p>
#endif
I'm doing exactly what is stated in the Laravel 5.1 docs:
Determining If An Item Exists In The Session
The has method may be used to check if an item exists in the session.
This method will return true if the item exists:
if ($request->session()->has('users')) { // }
Now this works perfectly fine for store method now, because I only added a flash_message there, but if I want to access another method like index, create, edit, etc. it shows this error:
ErrorException
Undefined variable: request
I understand that the request variable is not declared in the other methods and I can workaround this if-statement using isset($request).
Is there a better solution to check if my flash_message is set in the $request variable like in the earlier versions of Laravel?

It sounds like you're using controllers generated by Laravel.
If you look at the method definitions for store and update you'll find the parameter Request $request. By including this Laravel automatically creates a Request instance for you.
In order to access this in other methods you have three options:
Add the same parameter to any of the other method definitions and Laravel will generate it for you in the same way.
Create a constructor function and have it assign a Request instance to an attribute.
public function __construct(Request $request)
{
$this->request = $request;
}
Declare use Session; before the class definition to make the Session class accessible in your namespace.

You can still use the old method :) . latest laravel just added new ways to achieve that goal.here goes the sample code to display error messages which are passed as flash message into a view page .
Sample code
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Success</h4>
#if(is_array($message))
#foreach ($message as $m)
{{ $m }}
#endforeach
#else
{{ $message }}
#endif
</div>
#endif

Related

How do I use a controller for a "partial" view in Laravel?

Here is my situation. I have a layout.blade.php which most of my pages use. Within this file, I have some partial pieces that I include, like #include('partials.header'). I am trying to use a controller to send data to my header.blade.php file, but I'm confused as to exactly how this will work since it is included in every view that extends layout.blade.php.
What I am trying to do is retrieve a record in my database of any Game that has a date of today's date, if it exists, and display the details using blade within the header.
How can I make this work?
I think to define those Game as globally shared is way to go.
In your AppServiceProvider boot method
public function boot()
{
view()->composer('partials.header', function ($view) {
view()->share('todayGames', \App\Game::whereDay('created_at', date('d')->get());
});
// or event view()->composer('*', Closure) to share $todayGames accross whole blade
}
Render your blade as usual, partial.header blade
#foreach ($todayGames as $game)
// dostuffs
#endforeach
In Laravel you can create a service class method that acts like a controller and use #inject directive to access this in your partial view. This means you do not need to create global variables in boot(), or pass variables into every controller, or pass through the base view layout.blade.php.
resources/views/header.blade.php:
#inject('gamesToday', 'App\Services\GamesTodayService')
#foreach ($gamesToday->getTodayGames() as $game)
// display game details
#endforeach
While it's different value you retrieved belong of the game chosen, you can do something like that:
Controller
$data = Game::select('id', 'name', 'published_date')->first();
return view('game')->with(compact('data'));
layout.blade.php
<html><head></head><body>
{{ $date }}
</body></html>
game.blade.php
#extend('layout')
#section('date', $data->date)
#section('content')
#endsection
The better solution would be this
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))

Laravel flash or session messages not expiring [ not maintained Updated ]

Updated after some research
After some research I conclude that, my sessions are not maintained until I save them explicitly, below code works well, but WHY???? Ref here
Session::put('lets_test', 2);
Session::save();
Old Question
I'm new to laravel 5.3, and stuck at a problem. My Laravel Session or Flash messages are not expiring they display each time page is reloaded, until I use Session::flush() Below is my controller code
<?php
namespace App\Http\Controllers;
use Session;
use Auth;
use Illuminate\Http\Request;
use App\User;
use App\Hospital;
use App\Wpr;
use Helper;
class OperatorController extends Controller
{
public $user_detail;
public function __construct()
{
$this->middleware('auth');
$this->middleware('operator');
}
public function store (Request $request){ //Form is being submitted here
//My logic here
Session::flash('user_message', 'Thank You');
return redirect('/operator/wpr');
}
}
I've also used Session::set('user_message', 4);
and blade view
#if(Session::has('user_message'))
<div class="message animated tada">
{{ Session::get('user_message') }}
</div>
#endif
I've tried with Session::forget('user_message') but no luck.
Updating my post after some research. I've got somewhat close to my problem by reading this post on stack because this question is exactly same to my problem but unfortunately it still persists, I've changed my session storage from file to database (in case file permissions to storage directory). What might be other possibilities?
Please help, thanks in advance.
Ultimately, somehow, I managed to find solution for my problem, of not sustaining sessions. I don't think its any issue related to file permission. Now I'm saving my session explicitly and removing it explicitly.
Made a Helper class added two methods
public static function SetMessage($message, $type){
Session::put('user_message', $message);
Session::put('user_message_type', $type);
Session::save();
}
public static function ForgetMessage(){
Session::forget('user_message');
Session::forget('user_message_type');
Session::save();
}
and within Controller class
Helper::SetMessage('Record updated successfully', 'success');
and within blade view tempalte
#if(Session::has('user_message'))
<div class="alert alert-{{ Session::get('user_message_type') }}">
{{ Session::get('user_message') }}
{{ Helper::ForgetMessage('user_message') }}
</div>
#endif
I hope this might help someone who is facing such kind problem. But why is it so, still unknown, maybe one day I'll post the reason too. More suggestions are welcomed, if this could be done in a better way.
try this:
if(isset($_SESSION['user_message'])) {
$message = $_SESSION['user_message'];
unset($_SESSION['user_message']);
return $message;
}
In your (Laravel) blade add $request->session()->forget('key'); or Session::forget('key'); at the end of if loop this will end or delete the session of that key. This may help you for more reference about session of laravel 5.3 visit laravel 5.3

#if control structure not recognized - php laravel 5

I am programing a blog using Laravel 5 and bootstrap.
The #if control structure seem to not be working written this way in my blade.php:
#section('title')
#if($post)
<p> {{ $post->title}} </p>
#if(!Auth::guest() && ($post->name == Auth::user()->id || Auth::user()->is_admin()))
<button type="button" class="btn btn-default">Editer</button>
#endif
#endif
#endsection
Here is my function in PostController that calls the blade :
public function index()
{
$post = Post::get();
return view('posts.index', compact('post'));
}
I encounter this error :
Undefined property: Illuminate\Database\Eloquent\Collection::$title
I'm new to PHP, I can't seem to see where is the problem. If you have any clue, please help.
You need to attach a "post" variable when making a call to this view. In one of your controller methods.
In your edited question, "title" is missing. Pass a "title" variable along with post. Basically any variable you want to use in views that are not defined in view (except global variables), need to be passed to it explicitly from the controller.
Edit for collections error.
Your post variable is actually an array, loop through it and access title or any property of a post for each member of the post array

Setting anchor link to an address in Laravel, gives error

In my Laravel application, when I am trying to link the username of the person who has posted in the website with his profile page, with the code:
<div class="media-body">#{{ post.user.name }}
It is giving the error:
Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:
But, when I am trying to print #{{ post.user.profileUrl }} it is giving the right address, also in the json response, it is giving the right address, and going to the address is also reaching the specific location.
So, I don’t think it is some problem with post.user.profileUrl, as it seems to work fine, it seems to be some problem with using it with href, the address of the error in Google Chrome is:
http://localhost:8000/%7B%7B%20post.user.profileUrl%20%7D%7D
and the address should have been
http://localhost:8000/users/2 where 2 refers to the id of the user, which I am passing to the user through Vue.js
The problem is #{{ post.user.profileUrl }} is not parsing. %7B%7B%20post.user.profileUrl%20%7D%7D is ASCII representation of {{ post.user.profileUrl }}
Check if the code is in .blade.php file. If it is, you should look into JS template engine if you're using any.
https://laravel.com/docs/5.3/blade#blade-and-javascript-frameworks
The # symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework
I think you have a $post model in your view. When you setup relationships between the model Post and User you can link to them through the following:
#{{ $post->user->name }}
This will turn the users profileUrl into a valid link. But therefor you had to setup relationships in the Models.
Post model:
public function user() {
return $this->hasMany('App\Users', 'id', 'user_id');
//first parameter is the Model class
//send is the id of the user table
//thirth is the user_id in the post table
}
And in the User model:
public function posts() {
return $this->hasMany('App\Posts', 'user_id', 'id');
}
Hope this works!
Try this... this should definitely work for you
#verbatim
<div class="media-body">
<a href="{{ post.user.profileUrl }}">
{{ post.user.name }}
</a>
</div>
#endverbatim
I got my problem, the issue is with the javascript library, I am using, known as vue.js, it used to allow usage inside quotes, but in vue 2, they don't, so there is a turnaround for this,
<a :href="post.user.profileUrl">#{{ post.user.name }}</a>
and this works fine.
Thanks to all the people who contributed by answering...

laravel 4: always the fourth controller method doesn't work->blank page

All the first three methods of all my controller work well, but when i add a fourth one this one doesn't work (the construct method not included) and give me a blank page with the url of the controller action.
my controller class:
class StoreController extends BaseController{
public function __construct(){
parent::__construct();
$this->beforeFilter('csrf', ['on'=>'post']);
}
public function getIndex(){
return View::make('store.index', ['products'=>Product::take(4)->orderBy('created_at','DESC')->get()]);
}
public function getView($id){
return View::make('store.view', ['product'=>Product::find($id)]);
}
public function getCategory($cat_id){
return View::make('store.category', [
'products'=>Product::where('category_id','=',$cat_id)->paginate(6),
'category'=>Category::find($cat_id)]);
}
public function getSearch(){
$keyword=Input::get('keyword');
return View::make('store.search', [
'products'=>Product::where('title','LIKE','%'.$keyword.'%')->get(),
'keyword'=>$keyword]);
}
}
In my route.php file:
Route::controller('store', 'Storecontroller');
And the triggerer form of the action is:
<div id="search-form">
{{ Form::open(['url'=>'store/search', 'method'=>'get']) }}
{{ Form::text('keyword', null, ['placeholder'=>'Search by keyword', 'class'=>'search']) }}
{{ Form::submit('Search', ['class'=>'search submit']) }}
{{ Form::close() }}
as I said the getSearch method doesn't work and I'm given a blank page with the url of the action (not the returned view)
thanks
As the page is blank, make sure that debug is set to true in your app config (should be the topmost setting, preferably in the local dir). This means that when an error occurs you will be shown an error page with a detailed stack trace and error message, making it easier for you to debug your app.
Make sure that the view store.search exists, is named correctly (check for typos) and contains the html/php you need to display the $products.
Next, you have two possibilities:
Set a default value for the keyword input
// For example:
Input::get('keyword', 'default')
Check if there is a keyword specified
// For example:
if (Input::has('keyword')) {...} else {...}
As a side note: You should not perform (heavy) tasks inside of arrays like you do here. Put them inside variables and include them into the view array like you did with the keyword variable. Your code will also be more readable and maintainable. There's a lot more about this, but thats of the point here.
Let me know if this helped you.

Categories