How to pass array to flash message? - laravel

I want to send array of additional_feature that they are exist to flash message. Now i only send one additional_feature. Any suggestion how can i do that?
if(!empty($additional_features)){
foreach($additional_features as $additional_feature){
$data = [
'name' => $additional_feature,
];
if (!Feature::where('name', '=', $additional_feature)->exists()) {
$additional = Feature::firstOrCreate($data);
$additional_ids[] = $additional->id;
}
else{
return redirect()->back()->withFlashMessage($additional_feature . ' exists!');
}
}
}

You can use session() instead of with():
session->flash('someVar', $someArray);
Another thing you could try is to seriallize array and pass it as string. Then unserilize it and use.
Also, you could save an array using simple session:
session(['someVar' => $someArray]);
Then get it and delete manually:
session('somevar');
session()->forget('someVar');

We had the same problem and forked the package. you can find it here:
Forked at first from Laracasts/Flash to use multiple message
#if (Session::has('flash_notification.message'))
#if (Session::has('flash_notification.overlay'))
#include('flash::modal', ['modalClass' => 'flash-modal', 'title' => Session::get('flash_notification.title'), 'body' => Session::get('flash_notification.message')])
#else
<div class="alert alert-{{ Session::get('flash_notification.level') }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! Session::get('flash_notification.message') !!}
</div>
#endif
#endif
And the content of the include flash::modal
#if (Session::has('flash_notification.messages'))
#foreach (Session::get('flash_notification.messages') as $flashMessage)
#foreach($flashMessage as $type => $message)
<script>
$(function() {
var message = ('{{ $message }}<br>').replace(/'/g, "’");
customFlashMessage({
type: "{{ $type }}",
message: message
});
});
</script>
#endforeach
#endforeach
#endif

return redirect()->back()->with(['session1' => $value, 'session2' => $value]);
In the blade template:
{{ Session::get('session1') }}
{{ Session::get('session2') }}

Related

How to update user status using button without update all parameters in laravel

i want to update status user just pass parameter of 'status'.
this is my code, but i don't know, why i can not update user status. how to fix this problem?
my controller
public function activation()
{
// dd('test');
$action = Input::get('status');
if (Input::get('activate'))
{
$this->activateUser($action);
}
elseif (Input::get('inactivate'))
{
$this->deactivateUser($action);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
public function activateUser($user)
{
//dd('active');
User::findOrNew($user)->update(['status' => "1"]);
}
public function deactivateUser($user)
{
// dd('nonactive');
User::findOrNew($user)->update(['status' => "0"]);
}
my route
Route::post('admins-users/status', 'Backend\StatusController#activation');
my view
{!! Form::open(array('url' => 'admins-users/status')) !!}
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
After trying several ways. finally, i was found the answer for this problem using Ajax and select option. i add hash id before pass to controller and decode again in controller. i thinks id that pass must be concerned.
my controller
public function control(Request $request){
$status = $request->status;
$iduser = $request->iduser;
$key = Hashids::connection('main')->decode($iduser)[0] ?? abort(404);
$update = User::where('id', $key)->update(['status'=> $status]);
if($update)
{
return redirect(route('admins-users.index'))->with('message-post', 'Status user was updated successfully');
}
}
my form
using hash id to encode id user
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
{!! Form::hidden(null,$parameter, ['id'=> 'iduser'.$parameter ])!!}
{!! Form::select(
'status',
array(1=>'Active',0=>'Not Active'),
$user->exists ? $user->status : null,
[
'id' => 'action'.$parameter,
'placeholder' => 'Choose a status'
]
)
!!}
script
$(document).ready(function(){
#foreach($users as $user)
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
$("#action{{ $parameter }}").change(function(){
var status = $("#action{{ $parameter }}").val();
var iduser = $("#iduser{{ $parameter }}").val();
if(status==""){
alert("Please select an option");
}
else{
if (confirm('Do you want to change {{ $user->name }} status to {{ $user->status ? 'InActive' : 'Active' }}?')) {
$.ajax({
url: '{{ url("/action") }}',
data: 'status=' + status + '&iduser=' + iduser,
type: 'get',
success:function(response){
console.log(response);
}
});
document.location.reload();
}
}
});
#endforeach
});
Try with this
{!! Form::open(['url' => 'admins-users/status', 'method' => 'get' !!}
<input type="hidden" name="user_id" value="{{ $user->id }}">
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
Your route
Route::get('admins-users/status', 'Backend\StatusController#activation');
Your Controller Method
public function activation(Request $request)
{
$user_id = $request->user_id
if ($request->acticate) {
$this->activateUser($user_id);
}
elseif ($request->inactiavte) {
$this->deactivateUser($user_id);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
Hope this helps :)

Laravel 5 Pass and get a flash data not working

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

Laravel 4 :: custom validation error message is not displaying?

I'm trying to create an online form and to display my own error messages. But for some reason it's not working correctly. Here's my controller code, CategoryController.php:
class CategoryController extends BaseController
{
public function add()
{
return View::make('admin');
}
public function validate_add()
{
$rules = array('category_name' => 'Required|Alpha|Min:4');
$messages = array('category_name.Required' =>'Please enter the category name');
$input = Input::all();
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin')->withErrors($validator)->withInput(Input::all());
}
else
{
echo '<h1>WOW! your are are awesome!!! <3<h1> ';
}
}
}
And the admin.blade.php is following:
#extends('common')
#section('body')
<h1>Add Category</h1>
{{ HTML ::ul($errors->all(), array('class'=>'errors')) }}
{{ Form::open(array( 'url'=>'admin', $title="Admin Control Panel")) }}
<p>
{{ Form::label('Category Name:') }}
{{ Form::text('category_name', Input::old('category_name')) }}
</p>
<p>
{{Form::label('Parent Category') }}
{{ Form::select('Network', array('0' => 'Maincategory')) }}
</p>
<p>
{{ Form::submit('Submit') }}
</p>
{{ Form::close() }}
#stop
Interesting - I tried this on my local Laravel project and it looks like although you can specify your rules in mixed case, you need to specify the custom messages in lower case.
So if you changed your rules and your message override to; 'required' instead of 'Required' etc., it should work.

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources