Laravel 8 Flash Session not working on Request - laravel

I wonder in my application can't show flash message. I have tried many solutions on stackoverflow but my problem is not solved.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class DebugController extends Controller
{
public function get()
{
// Visit direct page flash session is working
// Eg: localhost/debug/get
// But if I send request all flash sessions are not working
return Redirect::route('home')->with('success', 'Working session on visit direct page!');
}
public function post(Request $request)
{
// All flash sessions are not working
session()->flash('anything', 'Session not working!');
// Working session
session()->put('message', 'Working session!');
// Session not working, is 'success' key reserved?
session()->put('success', 'Session not working!');
return Redirect::route('home')->with('anything', 'Session not working!'); // Session not working
}
}
Route:
Route::get('debug/get', 'DebugController#get');
Route::post('debug/post', 'DebugController#post');
View:
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
// Working session
#if(Session::has('message'))
<div class="alert alert-success">
{{ Session::get('message') }}
</div>
{{ session()->forget('message') }}
#endif
I have tried to modify middle ware in Kernel from this solution but still not working
Laravel Version: 8.x.x
PHP Version: 7.4.x

You will need to do Session::has('anything') in your view instead of Session::has('success').
The first parameter is the key that can be accessed with has or get.
If the above is already done, you might need to use the Facade: Session::flash('anything','content');
Take a look at this.
In case you want to remove the Session data
you have to use flush instead of flash().
Laravel documentation

Related

Fail to retrieve Post data with Laravel

I try to learn Laravel (v.9) from scratch but fail to do a simple basic task:
I just want to send "post_var" by POST request and display the var.
My form (blade template):
<form action="/post_and_show" method="POST">
#csrf
#method('post')
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
My Route (in web.php) with some dd() i tried to find the problem
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !!
// chrome debugger network tab show clearly its a POST request...
dd($request->all()); // returns empty Array
dd($request->post_var); // returns null
dd($request->getContent()); // returns string but i want param only
// "_token=yBBYpQ303a1tSiGtQF6zFCF6p6S7qadVfHMk4W7Q&_method=post&post_var=12345"
});
What am i doing wrong here?
Tried several methods i found in the documentation but non worked so far.
EDIT: I removed "#method('post')"
Btw.: My initial version that did not work either had no "#method('post')". I added it later on in the hope it might help...
<form action="/post_and_show" method="POST">
#csrf
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
But have still the same problems:
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !! but chrome says its a post request
dd($request->post_var); // returns null
dd($request->get('post_var'));// returns null
dd($request->getContent()); // returns complete body and header in one string
dd($request->all()); // return empty Array
});
EDIT 2:
Googleing i found "createFromGlobals":
use Illuminate\HTTP\Request; // just added this to show which class i use here...
use Illuminate\Support\Facades\Route;
Route::post('/post_and_show', function () {
dd(Request::createFromGlobals()->get('post_var')); // returning expected value
});
This works for me, but i can't find this method in documentation. Sorry, i am new to laravel and even php, so this seems all completely crazy to me.. ;-)
EDIT 3:
If i use a simple Controller it works too...
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
public function show(Request $request)
{
dd($request->post_var); // returns expected value...
}
}
Route:
Route::post('post_and_show', [FormController::class, 'show']);
So only in case i use the $request immediatly in the callback it does not work as expected. ( Either by design or bug??)

getting 404 modal when I do click event on Laravel livewire

I have started using livewire but I can't make it work im using a wire:click to load a form either on create mode or edit mode, but when I did click all I got was some sort of modal with 404 error
this is the livewire component
namespace App\Http\Livewire;
use Livewire\Component;
class Activities extends Component
{
public $view = 'none';
public function render()
{
return view('livewire.activities');
}
public function create_view(){
$this->view = 'create';
}
public function edit(){
$this->view = 'edit';
}
}
this is the view
<button wire:click="create_view" class="button-warning">{{ __('Create') }}</button>
#if ($view != 'none')
<div class="col-span-6">
#include("livewire.$view")
</div>
#endif
Edit: I load the view manually and it loads correctly, for example:
#if ($view != 'none')
<div class="col-span-6">
#include("livewire.edit")
</div>
#endif
if like you said this work then you have to check for the $view value. Always that you close the view remember change the property to the default value.
#if ($view != 'none')
<div class="col-span-6">
#include("livewire.edit")
</div>
#endif
I think you might be having a Livewire configuration issue. Check your installation and specifically your asset_url in your config/livewire.php if you have published your config
php artisan livewire:publish --config
The 404 modal should disappear once your config is correct.
If your livewire.php file in config not best config
this error should not disappear
make asset_url 'asset_url' asset_url => 'http://127.0.0.1:8000' (if you have localhost)
Change your code like this.
Because in your code the variable $view will consider part of string. So livewire is searching a page like livewire.$view. But in our case we didn't have like that filename. We have only the view file create. So change as per the code given below. It will work
<button wire:click="create_view" class="button-warning">{{ __('Create') }}</button>
#if ($view != 'none')
<div class="col-span-6">
#include('livewire.'.$view)
</div>
#endif

Undefined variable on Laravel

I´m a beginner starting with Laravel. I´m trying to show a question made on this website.
Here is the Controller page:
public function show($id)
{
//Use the model to get 1 record from the database
$question = $Question::findOrFail($id);
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
I have included at the top of the file:
use App\Question;
Here is my blade page:
#section('content')
<div class="container">
<h1> {{ $question->title }} </h1>
<p class="lead">
{{ $question->description }}
</p>
<hr />
</div>
#endsection
In the model I have not defined anything since I don´t need to specify any special rule. And finally here is the Route:
Route::resource('questions', 'QuestionController');
I got the error "ErrorException Undefined Variable: Question" and supposedly the error is on:
$question = $Question::findOrFail($id);
I´m looking forward to your observations.
Kind Regards.
You just need to change the controller section
public function show($id)
{
//Use the model to get 1 record from the database
$question = Question::findOrFail($id); // here is the error
//show the view and pass the record to the view
return view('questions.show')->with('question', $question);
}
Explanation:- You are going to use a variable $Question that is not defined. This is the basic PHP error, not the laravel issue.
However, You are using the "App\Question" model class not a sperate variable.

laravel-5.7: data is not saving into database, Object not found

I'm trying to save data into db but its not saving and says that object not found, can anyone suggest me solution, i am following this tutorial: https://laracasts.com/series/laravel-from-scratch-2018/episodes/10
controller:
public function index()
{
$projects = Project::all();
return view('projects.index', compact('projects'));
}
public function create()
{
return view('projects.create');
}
public function store()
{
$project = new Project();
$project->title = request('title');
$project->description = request('description');
$project->save();
return redirect('/projects');
}
routes:
Route::get('/projects','ProjectsController#index');
Route::post('/projects','ProjectsController#store');
Route::get('/projects/create','ProjectsController#create');
create.blade.php:
<form method="POST" action="/projects">
{{ csrf_field() }}
<div>
<input type="text" name="title" placeholder="Project title">
</div>
<div>
<textarea name="description" placeholder="Project description"></textarea>
</div>
<div>
<button type="submit">Create Project</button>
</div>
</form>
index.blade.php:
#foreach($projects as $project)
<li>{{ $project->title }}</li>
#endforeach
You have missed out passing request parameter in the controller store()
public function store(Request $request)
{
$project = new Project();
$project->title = $request->title;
$project->description = $request->description;
$project->save();
return redirect('/projects');
}
And also don't forget to include use Illuminate\Http\Request; above(outside) controller class.
The Laravel code you've posted is correct under a properly configured website. The error from your comments:
Object not found! The requested URL was not found on this server. The
link on the referring page seems to be wrong or outdated. Please
inform the author of that page about the error. If you think this is a
server error, please contact the webmaster. Error 404 localhost
Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.7
is an Apache error page, which means it's not requesting a page from your laravel project at all. The data is probably saving in your database, but then you redirect away to a page that is outside your project, and Apache can't find it.
Your website is located at http://localhost/laravel/public, which means you need to access the projects page at http://localhost/laravel/public/projects. However, redirect('/projects') gives you an absolute path instead of a relative path, sending you to http://localhost/projects, which does not exist.
Solutions
Since this is a local development project, I'm going to skip the issues with the improper Apache configuration and focus on other ways to avoid the error.
Option 1
Use a named route:
Route::get('/projects','ProjectsController#index')->name('projects.index');
and use the name of the route for the redirect:
return redirect()->route('projects.index');
This should generate correct urls within your project.
Option 2
Use serve for development instead of Apache.
Open a terminal in your Laravel project directory and run this command:
php artisan serve
This will start PHP's built-in webserver at http://localhost:8000, skipping Apache entirely. During development this is perfectly fine.

Making object accessible throughout application

I am adding user notifications to my system. To access these notifications for a user, I call an API I have created in another system. So, my IndexController looks something like the following
public function index()
{
if ($user = Sentinel::getUser()) {
$notifications = MyAPI::returnNotifications($user->id);
return view('centaur.dashboard', compact('notifications'));
}
}
Now to problem with the above is that notifications is now only available on the dashboard view. Within my header view I have something like this
#if($notifications)
#foreach($notifications as $notification)
<a class="content" href="#">
<div class="notification-item">
<h4 class="item-title">{{ $notification->subject }}</h4>
<p class="item-info">{{ $notification->body }}</p>
</div>
</a>
#endforeach
#endif
But if I now visit another page besides the dashboard page I get a Undefined variable: notifications error. This is because header is on every page, but I am only passing my notification object to the dashboard page.
Is there any way to make this notification object universally available?
Thanks
UPDATE
if($user = Sentinel::getUser()) {
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id));
});
}
You can use a view composer. In your App\Providers\AppServiceProvider#boot method add:
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id););
});
Now you'll have the variable $notifications in all of your views. If you want it for specific ones just replace the * with the view name.

Resources