Flash messages display and sometimes they don't - laravel

I'm using a spatie/laravel-flash for displaying some flash messages. It works when I use simple HTML forms, but when I use Vue.js templates, the message doesn't show. (and sometimes they don't) after submitting the form and go to the next request.
main layout
<div class="col-lg-12 mb-2">
#include('layouts.partials.flash_message')
</div>
<section class="py-5">
#yield('content')
</section>
layouts.partials.flash_message
#if(flash()->message)
<div class="{{ flash()->class }} alert-dismissible" role="alert">
<button type="button" class="close close-white" data-dismiss="alert">×</button>
{{ flash()->message }}
</div>
#endif
create.blade.php
#extends('layouts.main_layout')
#section('content')
<create-school> </create-school>
#endsection
Vue.js template store() method
store()
{
axios.post('/master/schools', {
name: this.name,
}.then((response) => {
this.name = ''
}));
}
Laravel store method
<?php
public function store(Request $request)
{
$school = School::create([
'name' => $request->name,
]);
flash('success message', 'alert alert-success');
return back();
}

Since you are using ajax to store your data, you will need to provide the message as a response in that request. So basically the store method on your controller would look like
public function store(Request $request)
{
$school = School::create([
'name' => $request->name,
]);
return response($school, 201);
}
201 is the HTTP code to indicate a resource was created, and the by the RFC you should return the resource in the response.
In your Vue file, the store method would then be
store()
{
axios.post('/master/schools', {
name: this.name,
}.then((response) => {
this.name = ''
// Modify your DOM or alert the user
alert('Resource created')
}));
}
As a recomendation, you should aways validate user input before storing.

Related

Laravel 9 how to pass parameter in url from one controller to another controller?

I was facing this problem of missing parameter when trying to pass a parameter from one controller to another controller. The parameter is $id whereby the data is originally from post method in details blade.php into function postCreateStepOne However, I want to pass the data into a new view and I return
redirect()->route('details.tenant.step.two')->with( ['id' => $id]
);}
And this is where error occur. However, it works fine if I skip it into a new route and directly return into a view with the compact parameter. For Example,
return view('document.details-step-two', compact('id', 'property'));
However, I would prefer a new url as I was doing multistep form using Laravel.
Error
web.php
Route::get('/document/details/viewing/{id}', 'ViewDetails')->name('details.tenant');
Route::post('/document/details/viewing/{id}', 'postCreateStepOne')->name('post.step-one');
Route::get('/document/details/viewing/step-2/{id}', 'ViewDetailsStep2')->name('details.tenant.step.two');
TenanatController.php
public function viewDetails($id){
$view = Properties::findOrFail($id);
return view('document.details', compact('view'));
}
public function ViewDetailsStep2(Request $request, $id){
$view = Properties::findOrFail($id);
$property = $request->session()->get('property');
return view('document.details-step-two', compact('view', 'property'));
}
public function postCreateStepOne($id, Request $request)
{
$validatedData = $request->validate([
'property-name' => 'required',
]);
if(empty($request->session()->get('property'))){
$property = new Tenancy();
$property->fill($validatedData);
$request->session()->put('property', $property);
}else{
$property = $request->session()->get('property');
$property->fill($validatedData);
$request->session()->put('property', $property);
}
return redirect()->route('details.tenant.step.two')->with( ['id' => $id] );
}
details.blade.php
<form action="{{ route('post.step-one', $view->id) }}" method="POST">
#csrf
<div class="card-body">
<div class="form-group">
<label for="title">Property Name:</label>
<input type="text" value="" class="form-control" id="property-name" name="property-name">
</div>
</div>
<div class="card-footer text-right">
<button type="submit" class="btn btn-primary">Next</button>
</div>
</form>
When you use with on a redirect the parameter is passed through the session. If you want to redirect to a route with a given route parameter you should pass that parameter in the route function itself like e.g.
return redirect()->route('details.tenant.step.two', ['id' => $id]);

How do I get my variable to show in my store function

This is probably a very simple thing, but for some reason I just can't figure it out. I created a function that gets the images from my vue component.
What I'm trying to do is take the images from my postImage() and have them in my store() function, so that I can save everything into the database.
The problem I'm getting is when I do that I get this error
Too few arguments to function App\Http\Controllers\Admin\CategoryController::store(), 1 passed and exactly 2 expected
I do understand that the error is telling me that only the $request was sent and not the $image. I'm not sure how to get it working. If I've left anything out please let me know
Here is my controller
public function store(Request $request, $image)
{
$category = new Category();
$input = $this->safeInput($request);
$category->fill($input);
dd($image);
$slug = $category->slug($category->title);
$category->slug = $slug;
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category_order = $category->order_number();
$category->order = $category_order;
$category->save();
}
public function postImage(Request $request)
{
if($request->hasFile('image'))
{
$names = [];
foreach($request->file('image') as $image)
{
$destinationPath = 'product_images/category/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
array_push($names, $filename);
}
$image = json_encode($names);
return $image;
}
}
This is my vue component
<template>
<div class="container">
<div class="uploader"
#dragenter="OnDragEnter"
#dragleave="OnDragLeave"
#dragover.prevent
#drop="onDrop"
>
<div v-show="!images.length" :value="testing()">
<i class="fas fa-cloud-upload-alt"></i>
<div>OR</div>
<div class="file-input">
<label for="file">Select a file</label>
<input type="file" id="file" #change="onInputChange" multiple>
</div>
</div>
<div class="images-preview" v-show="images.length">
<div class="img-wrapper" v-for="(image, index) in images">
<img :src="image" :alt="`Image Uplaoder ${index}`">
<div class="details">
<span class="name" v-text="files[index].name"></span>
<span class="size" v-text="getFileSize(files[index].size)"></span>
</div>
<div class="btn btn-danger" #click="funDeleteFile(index)">
Remove
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
isDragging: false,
//Sets the dragCount to 0
dragCount: 0,
//Makes files an array, so that we can send the files to the server
files: [],
//Makes images an array, so that we can let the user see the images
images: [],
}
},
methods: {
testing() {
console.log('This is submit images - '+this.files);
var formData = new FormData();
this.files.forEach(file => {
formData.append('image[]', file, file.name);
});
axios.post('/admin/category/post-image', formData);
},
OnDragEnter(e) {
//Prevents the default action of the browser
e.preventDefault();
// This lets the dragCount become 1, so that the image uploader changes colour
this.dragCount++;
// Changes the isDragging variable to true instead of false
this.isDragging = true;
return false;
},
OnDragLeave(e) {
//Prevents the default action of the browser
e.preventDefault();
// This lets the dragcount become 0, so that the image uploader changes to it's original colour
this.dragCount--;
// This is if the dragCount is <= 0 then the isDragging variable is false
if (this.dragCount <= 0)
this.isDragging = false;
},
onInputChange(e) {
// Grabs the files from the event
const files = e.target.files;
// Creates an array for files, so that we can loop thru it
// Send the file to the addImage method via "this.addImage(file)"
Array.from(files).forEach(file => this.addImage(file));
},
onDrop(e) {
//Prevents the default action of the browser
e.preventDefault();
//Stops the propagation into the other elements inside the one we drop and file into
e.stopPropagation();
// This is to disable the dragging of the images
this.isDragging = false;
// Grabs the files from the event
const files = e.dataTransfer.files;
// Creates an array for files, so that we can loop thru it
// Send the file to the addImage method via "this.addImage(file)"
Array.from(files).forEach(file => this.addImage(file));
},
addImage(file) {
//Checks if the file type is an image
if (!file.type.match('image.*')) {
this.$toastr.e(`${file.name} is not an image`);
return;
}
this.files.push(file);
const img = new Image(),
reader = new FileReader();
reader.onload = (e) => this.images.push(e.target.result);
reader.readAsDataURL(file);
},
}
}
</script>
my create.blade.php
#extends('layouts.admin')
#section('content')
#component('admin.components.products.category-form', [
'formUrl' => route('category.store'),
'formMethod' => 'POST',
'model' => $category,
'category_id' => $category_id,
'image' => '',
'image2' => ''
])
#endcomponent
#endsection
and my form
{{ Form::model($model, array('url' => $formUrl, 'method' => $formMethod, 'class' => 'add-form', 'files' => true)) }}
<div class="form-group">
{{ Form::label('category_id', 'Parent Category') }}
{{ Form::select('category_id', $category_id->prepend('Please Select', '0'), null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
<label>Active:</label>
{{ Form::checkbox('active', 0) }}
</div>
<div id="app" class="mb-20">
<category-image></category-image>
</div>
<div class="form-group">
{{ Form::submit('Save', array('class' => "btn btn-dark btn-lg btn-block")) }}
</div>
{{ Form::close() }}
My routes
Route::resource('admin/category', 'Admin\CategoryController');
Route::post('admin/category/post-image', 'Admin\CategoryController#postImage')->name('admin.category.post-image');
UPDATE
I've tried this to pass the image to a hidden field in my form so that I can grab it in the $request in my store function.
In my CategoryController#create
$category = new Category();
$category_list = Category::with('parentCategory')->get();
$category_id = Category::pluck('title', 'id');
// I've added this.
$image = '';
return view('admin.products.category.create', compact('category', 'category_list', 'category_id', 'image'));
in my CategoryController#postImage
//I've added this to, so that I can pass the image variable to the create.blade.php
return redirect()->route('category.create', compact('image'));
then in my create.blade.php I added
'my_image' => $my_image
and in my category-form.blade.php component I added
<div id="app" class="mb-20">
<category-image></category-image>
<input type="hidden" name="image" id="image" value="{{ $my_image }}">
</div>
at the moment I haven't been able to do that either. Though I'm not sure if this is the right way to go, I'm a bit worried that some random person can then add whatever they want by using the hidden input
For what do you have the parameter $image? This is not specified in your axios.post.
public function store(Request $request)
{
$category = new Category();
$input = $this->safeInput($request);
$category->fill($input);
dd($this->postImage($request));
$slug = $category->slug($category->title);
$category->slug = $slug;
if($request->has('active'))
{
$category->active = 1;
}else{
$category->active = 0;
}
$category_order = $category->order_number();
$category->order = $category_order;
$category->save();
}
public function postImage($request)
{
if($request->hasFile('image'))
{
$names = [];
foreach($request->file('image') as $image)
{
$destinationPath = 'product_images/category/';
$filename = $image->getClientOriginalName();
$image->move($destinationPath, $filename);
array_push($names, $filename);
}
$image = json_encode($names);
return $image;
}
}
If the $request is available there, Then there is no need to pass extra $image variable.
have you tried
dd($request)
or
print_r($request->toArray()); exit;
for see what's in your request!
In your create.blade you use 'formUrl' => route('category.store'), this route calls the "store" method, right? If so, it also needs to pass the $image parameter. It would be easier to identify the problem if we could se your web routes file too.
If route('category.store') does call the store method you have a few options.
1 - If you don't really need the $image parameter for the store method, you could just remove it.
2 - If you need it in a few cases, just make the parameter optional and check if it's received before handling it. Example: store(Request $request, $image = null)
3 - If this parameter actually is required, you will have to pass it everytime, even when calling routes. Example: route('category.store', ['image' => $something]). Looking at your code at this moment in create.blade you don't have the content to pass though, so I don't think this is an option.
The problem isn't the image missing in the request object sent through the form, it is the second parameter required by the category.store method.
Even if you now send the image in the form with a hidden field, you would still need to pass it as a parameter everytime you call the category.store.
Your store method is defined like
store(Request $request, $image)
So, when you call this method, even if you're just getting the route URL with route('category.store'), you do need to send the image parameter in this call.
Example:
route('category.store', ['image' => 'image id here']);
The same goes for the route definition in your web routes file. You're using a resource route, but laravel don't expect a second parameter for the store method in a default resource, so you will need to change that.
/*
adds exception to the resource so it will not handle the store method
*/
Route::resource('admin/category', 'Admin\CategoryController')->except(['store']);
//adds a custom route that supports the $image parameter.
Route::post('admin/category/{image}', 'Admin\CategoryController#store')
Now, if you're planning to send the image through the request object, you don't need it as a second parameter, so the only thing you will need to change is to make your category.store method like that.
public function store(Request $request)

Laravel post error

I'm getting the following error message when trying to update user data:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
I'm logging the user in, then want to give them the option to change their preferences. The form displays fine in the view but won't post.
Here are my routes:
Route::prefix('admin')->group(function(){
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminsController#index')->name('admin.dashboard');
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
Here's the Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Admin;
use Auth;
class AdminsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$id = Auth::user()->id;
$admin = Admin::find($id);
return view('admin')->with('admin',$admin);
}
public function update(Request $request, $id)
{
$this-> validate($request, [
'target_sector' => 'required|max:255',
'target_skillsets' => 'required|max:255',
'target_companies'=> 'required|max:255',
'target_locations'=> 'required|max:255',
]);
//Create Post
$id = Auth::user()->id;
$admin = Admin::find($id);
$admin->target_sector = $request->input('target_sector');
$admin->target_skillsets = $request->input('target_skillsets');
$admin->target_companies = $request->input('target_companies');
$admin->target_locations = $request->input('target_locations');
$admin->save();
return redirect('/admin')->with('success', 'Preferences Updated', 'admin',$admin);
}
}
And here is the view:
#include('includes.nav_login')
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row mt-4">
<div class="col-md-10 offset-md-1">
<div class="card">
<div class="card-header">Admin Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
You are logged in as ADMIN!
</div>
<div class="card-header">Update Vacancy Preferences</div>
<div class="card-body">
{!! Form::open(['action' => ['AdminsController#update', $admin], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('companies', 'Companies')}}
{{Form::text('companies', $admin->target_companies,['class'=>'form-control', 'placeholder'=>'Target Companies'])}}
</div>
<div class="form-group">
{{Form::label('skillsets', 'Skillsets')}}
{{Form::text('skillsets', $admin->target_skillsets,['class'=>'form-control', 'placeholder'=>'Skillsets'])}}
</div>
<div class="form-group">
{{Form::label('sector', 'Sector')}}
{{Form::text('sector', $admin->target_sector,['class'=>'form-control', 'placeholder'=>'Sector'])}}
</div>
<div class="form-group">
{{Form::label('locations', 'Locations')}}
{{Form::text('locations', $admin->target_locations,['class'=>'form-control', 'placeholder'=>'Locations'])}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Update',['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
Can anyone explain why this isn't working?
You should fix you route, because you are using put method for update, but on routes, you defined as post
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
Therefore error occurs.
You should fix your route like this,
Route::put('/{id}', 'AdminsController#update')->name('admin.dashboard.update');
I hope this help you.
The error says MethodNotAllowed which means you are hitting a route with a different request method than it accepts
you open the form like this
{!! Form::open(['action' => ['AdminsController#update', $admin], 'method' => 'POST']) !!}
so till now the form method is POST
but then you spoof the method to be of type put
{{Form::hidden('_method', 'PUT')}}
so now the method becomes of type put not post
however your route expects the method to be post
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
This is why you get method not allowed exception
you either change the method on your controller to be put instead of post or remove the method spoofing thing from inside your form
I mean this line
//remove this
{{Form::hidden('_method', 'PUT')}}
once you fix it you will have another error because you don't have csrf field in your form so just add this inside of your form
#csrf
Really appreciate both answers on here - thanks #Mohammad Instanboli and #webdevtr.
Webdevtr was right to advise this:
Route::put('/{id}', 'AdminsController#update')->name('admin.dashboard.update');
I also had to go back and fix the following which I thought would be useful to note if anyone else views this with a similar issue:
Firstly my AdminsController#update method needed the following changes:
I changed the public function update to take one less variable - ($id)
public function update(Request $request)
{
$this-> validate($request, [
'target_sector' => 'required|max:255',
'target_skillsets' => 'required|max:255',
'target_companies'=> 'required|max:255',
'target_locations'=> 'required|max:255',
]);
//Create Post
$id = Auth::user()->id;
$admin = Admin::find($id);
$admin->target_sector = $request->input('target_sector');
$admin->target_skillsets = $request->input('target_skillsets');
$admin->target_companies = $request->input('target_companies');
$admin->target_locations = $request->input('target_locations');
$admin->save();
return redirect('/admin')->with('success', 'Preferences Updated', 'admin',$admin);
}
Then I needed to make sure the $request->input('x') matched the input names in the form in my view - i.e:
<div class="form-group">
{{Form::label('target_sector', 'target_sector')}}
{{Form::text('target_sector', $admin->target_sector,['class'=>'form-control', 'placeholder'=>'Sector'])}}
</div>

Laravel 5.2.26 get form validation data array

I submit the form and have some validation mean email,require,unique email,
when validation have error message then laravel 5.2 return validation return array.
I guess you want to retain the submitted data on error.
Considering a sample
public function postJobs(Request $request) {
$input = $request->all();
$messages = [
'job_title.required' => trans('job.title_required'),
];
$validator = Validator::make($request->all(), [
'job_title' => 'required'
], $messages);
if ($validator->fails()) { // redirect if validation fails, note the ->withErrors($validator)
return redirect()
->route('your.route')
->withErrors($validator)
->withInput();
}
// Do other stuff if no error
}
And, in the view you can handle errors like this:
<div class="<?php if (count($errors) > 0) { echo 'alert alert-danger'; } ?>" >
<ul>
#if (count($errors) > 0)
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
#endif
</ul>
</div>
And if you want the input data, you need to redirect with ->withInput(); which can be fetch in view like:
Update
<input name= "job_title" value="{{ Request::old('job_title') }}" />
But, the best thing is to use laravel Form package so they all are handled automatically.
If you just need form data, you can use Request object:
public function store(Request $request)
{
$name = $request->input('firstName');
}
https://laravel.com/docs/5.1/requests#accessing-the-request
Alternatively, you could use $request->get('firstName');
Use old() to get previous value from input. Example:
<input name="firstName" value="{{old('firstName')}}">
See documentation here https://laravel.com/docs/5.1/requests#old-input

Validation error in Laravel - $errors array does not get populated after the validation failure

I've ran into a strange issue regarding validations in Laravel 5.2. I reviewed following questions on StackOverflow, but none of them seems to apply to my case:
Laravel validation not showing errors
Laravel Validation not returning error
The thing is, that I am trying to validate a title field, before persisting the Card object into the database. When I submit the form with an empty title field, as expected, It doesn't pass the validations. However, the $errors array doesn't get populated upon failure of the mentioned validations. Can anybody explain where am I going wrong with this code?
/////////////////////// CONTROLLER /////////////////////
public function create(Request $request)
{
$this->validate($request, [
'title' => 'required|min:10'
]);
Card::create($request->all());
return back();
}
///////////////////////// VIEW /////////////////////////
// Show errors, if any. (never gets triggered)
#if(count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<form method="POST" action="/cards">
{{ csrf_field() }}
<div class="form-group">
// The textarea does not get populated with the 'old' value as well
<textarea class="form-control" name="title">{{ old('title') }}</textarea>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Add Card</button>
</div>
</form>
If you are running Laravel 5.2.27 and up, you no longer need to use the web middleware group. In fact, you shouldn't add it to your routes because it's now automatically applied by default.
If you open up your app/Http/RouteServiceProvider.php file, you will see this bit of code:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Source: https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L53
As you can see, it's automatically applying the web middleware for you. If you try to apply it again (more than once) in your routes file, you'll run into weird problems like what you are currently facing.
In order to find out the version of Laravel that you are running, run this command: php artisan --version
I guess you have to set the if clause to #if(count($errors) > 0)
In your controller, try adding a $validator->fails() statement, and using ->withErrors() to return any errors to your template.
public function create(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|min:10'
]);
if ($validator->fails()) {
return back()->withErrors($validator);
}
Card::create($request->all());
return back();
}

Resources