I am developing a package with a contact form in Laravel. I'm trying to set & get session data, but it's not working with the following.
View
#if(session('success'))
<div class="alert alert-success alert-dismissible">
×
{{session('success')}}
</div>
#endif
Controller
public function store(Request $request)
{
//Validation
$request->validate([
'email'=>'required|max:50|unique:contact_forms,email'
]);
//Data
$contact_form = new ContactForm();
$contact_form->full_name = $request->full_name;
$contact_form->mobile = $request->mobile;
$contact_form->email = $request->email;
//Save
$contact_form->save();
//Return back
return back()->with('success','Record inserted successfully');
}
Route
Route::group(['namespace' => 'W3public\ContactForm\Http\Controllers'], function () {
Route::get('contact-us', 'ContactFormController#index');
Route::post('contact-us', 'ContactFormController#store')->name('contact-us');
});
How can I set/get session data in package development in Laravel?Thanks in advance.
Best way of doing this is flash session messages
Redirect as
$request->session()->flash('alert-success', 'Record inserted successfully!');
and in your view file
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to add validation in the controller but it does not work with auth:check. This is the Laravel version 5.7.
This is the function store that has a problem with the validation.
public function store(Request $request)
{
$request->validate([
'first_name' => ['required'|'min:2'|'max:50']
]);
if(Auth::check()){
$player = Player::create([
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name'),
]);
if($player){
return redirect()->route('players.show', ['player'=> $player->id])
->with('success' , 'foo');
}
}
return back()->withInput()->with('errors', 'Foo Error');
}
This is the error message:
[![enter image description here][2]][2]
Update
The validation works now but it generated a new problem. When I save a new player it's shows me this error.
I think the problem is this code
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ $player->first_name }} {{ $player->last_name }} <span class="float-right"><a class="" href="{{ route('players.edit', $player->id)}}">
{{ __('Spieler bearbeiten') }}
</a></span></div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<ul>
<li>Vorname: {{ $player->first_name }}</li>
<li>Nachname: {{ $player->last_name }}</li>
<li>Land: {{ $player->country }}</li>
<li>Bild: {{ $player->image }}</li>
<li>Grösse: {{ $player->size }}</li>
<li>Gewicht: {{ $player->weight }}</li>
<li>Alter: {{ $player->date_of_birth }}</li>
</ul>
<br>
<br>
Zurück
</div>
</div>
</div>
</div>
</div>
#endsection
Most of your code is unnecessary, you can protect the route and get rid of most of it:
public function store(Request $request)
{
// Your validation is not correct and you are missing the last_name.
// $request->validate() will return the validated data if
// the validation was successful
$request->validate([
'first_name' => ['required' | 'min:2' | 'max:50']
]);
// After protecting the route we can get rid of the auth check
if (Auth::check()) {
$player = Player::create([
// Since $request->validate returns the validated data, this is unncessary
'first_name' => $request->input('fist_name'),
'last_name' => $request->input('last_name'),
]);
// It will either create the player or throw an exception,
// this conditional seems unnecessary
if ($player) {
return redirect()
// If you setup your routes correctly you can pass the model to the route
// so ['player' => $player->id] is unnecessary
->route('players.show', ['player' => $player->id])
->with('success', 'foo');
}
}
// This return seems pointless since it can never be reached
// after protecting the route
return back()->withInput()->with('errors', 'Foo Error');
}
So it would look something like this:
public function __construct()
{
$this->middleware('auth');
}
/**
* #param Request $request
*
* #return RedirectResponse
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required|min:2|max:50',
'last_name' => 'required|min:2|max:50',
]);
$player = Player::create($validatedData);
return redirect()
->route('players.show', $player)
->with('success', 'foo');
}
This did not show the errors after submit
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
$this->validate($request,[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
Inserting values into the database.I want to validate on submitting the form
public function store(Request $request)
{
//
$this->validate($request->all(),[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
I displayed errors like this, but not working for me
#if(count($errors) > 0)
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
Add this piece of code on your controller method.
return back()->withErrors()->withInput()
you can also access old input value with old(field_name)
Use ->all() here to provide all input value in to validate
$this->validate($request->all(),[
Or you can try like this
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
And display error as
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
first, edit your method like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
use Validator;
and inside this method please edit your redirect route and make sure your redirect url, redirect you in the page that had the error message:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
if ($validator->fails()) {
return redirect(route('make your route here '))
->withErrors($validator)
->withInput();
}
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
and for displaying error messages inside your blade template make this :
#if(!empty($errors))
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
#endif
#endif
Maybe is something simple but can't understand why I don't see my message.
I have this in the controller after the function is submitted
return redirect()->route('item.show', $id)->with('alert-success', ' Review submitted successfully.');
And this in item page
#foreach (['danger', 'warning', 'success', 'info','message'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
The form is submitted successfully, data is saved in the database, the page is reloaded but the message does not appear for success.
update
array(4) {
["_token"]=>
string(40) "snB4uoaR087wrvXOuh8epR56cjtC2OCSmZJd9smn"
["_previous"]=>
array(1) {
["url"]=>
string(29) "http://example.com/item/17"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
["login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"]=>
int(9)
}
Route
Route::group(['namespace' => 'Frontend', 'middleware' => 'web'], function () {
Route::post('items/review/{item}', 'ItemController#reviewSubmit')->name('item.review');
....
}
Use flash for message stuffs:
Controller
$request->flash('alert-success', ' Review submitted successfully.');
return redirect()->route('item.show', $id);
item page:
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div>
Check about flash message with laravel documentation
NOTE: Make sure the middleware not applied twice, this is also be the cause of this issue. Check this
I am trying to return a flash message depending on the outcome of an function however I don't really know how to do this properly, can someone help me with fixing this?
Controller:
public function postDB(Requests\NameRequest $request) {
$newName = trim($request->input('newName'));
$newLat = $request->input('newCode');
$websites = new Website();
$websites->name = $newName;
$websites->html = $newLat;
$websites->save();
if ($websites->save())
{
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', 'Profile updated!');
}
Request:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'img' => 'file|image',
];
}
public function messages()
{
return [
'img.image' => 'File type is not supported! Use files with extension .jpg/.jpeg/.gif',
];
}
Template:
#if (session('status'))
#if (session('status')=="success")
<div class="alert alert-success">
{{ session('message') }}
</div>
#else
<div class="alert alert-error">
{{ session('message') }}
</div>
#endif
#endif
Route:
Route::group(['middleware' => ['web']], function () {
Route::get('home', 'BuilderController#homepage');
Route::get('pages', 'BuilderController#websites');
Route::get('template', 'BuilderController#templates');
Route::post('template2', 'BuilderController#postDB');
Route::post('template', 'BuilderController#testing');
Route::get('logout', 'BuilderController#getLogout');
Route::get('/website/{name}', 'BuilderController#website');
});
Solution :
There could be only one reason for this issue.
The laravel will pass the flash messages only if it's registered inside the middleware web
i.e.,
Route::group(['middleware' => ['web']], function () {
//The back()'s url should be registered here
});
Update :
It seems you need to redirect back with message and inputs
So, You can do like this
if ($request->hasFile('img')) {
$message = 'success';
} else {
$message = 'error';
}
return redirect()->back()->withInput()->->with('message', $message);
Update 2 :
#if (session('status'))
#if (session('status')=="success")
<div class="alert alert-success">
Congrats! Everything was fine
</div>
#else
<div class="alert alert-error">
Oops! Something went wrong
</div>
#endif
#endif
Note : You can pass the status param to your wish
If you pass message as a flash parameter name, use it, not status.
#if (session('message'))
#if (session('message')=="success")
<div class="alert alert-success">
Congrats! Everything was fine
</div>
#else
<div class="alert alert-error">
Oops! Something went wrong
</div>
#endif
#endif
i want to pass a flash data from store function to add function but i cant get it to work, i always get null;
here is my controller
public function add()
{
return view('cars.add');
}
public function store(CarFormRequest $request)
{
$car = new Cars(array(
'name' => $request->get('name'),
'color_id' => $request->get('color')
));
$car->save();
$car->position_id = $car->id;
$car->save();
return redirect('/cars/add')->with('status', 'A Car has been added');
}
here is my view:
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
Add in your controller
session()->flash('status', 'Task was successful!');
and in View:
#if (session->has('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif