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.
Related
I am using Laravel 5.4
my create form is multi feild for multi language. name of field in my form is variable:
{!! Form::open(['route' => 'pages.store','files'=>true]) !!}
#if( isset($languages) && $languages->count() > 0 )
#foreach($languages as $language)
<div class="form-group">
{!! Form::label('subject_'.$language->code, 'subject in '.$language->name) !!}
<div class="form-line">
{!! Form::text('subject_'.$language->code,old('subject'),['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
<!-- TinyMCE -->
{!! Form::textarea('content_'.$language->code,'',['class'=>'tinymce']) !!}
<!-- #END# TinyMCE -->
</div>
#if (!$loop->last)
<hr class="style18">
#endif
#endforeach
<div class="form-group">
{!! Form::submit('save change',['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
and my control code:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'subject' => 'required|max:255',
'content' => 'required|max:255',
]);
$languages = Languages::all();
$page = new Page();
$page->save(); // Eloquent
foreach ($languages as $language) {
$pageTrans = new PageTrans();
$pageTrans['page_id']= $page->id;
$pageTrans['locale'] = $language->locale;
$pageTrans['subject'] = $request->input('subject_' . $language->code);
$pageTrans['content'] = $request->input('content_' . $language->code);
$pageTrans->save(); // Eloquent
}
return redirect(route('pages.index'));
}
but problem with validat and not detect feild name. Do you know of a solution or a better way to do this?
You can change your controller same this. I didn't test. Please let me know if have any problem on that.
$languages = Languages::all();
if( $languages->count() ){
$data = [];
foreach ($languages as $language) {
$data['subject_'.$language->code] = 'required|max:255';
$data['content_'.$language->code] = 'required';
}
$validator = Validator::make($request->all(), $data);
if ($validator->fails()) {
return redirect(route('pages.store'))
->withErrors($validator)
->withInput();
}else{
$page = new Page();
$page->save(); // Eloquent
foreach ($languages as $language) {
$pageTrans = new PageTrans();
$pageTrans['page_id']= $page->id;
$pageTrans['locale'] = $language->locale;
$pageTrans['subject'] = $request->input('subject_' . $language->code);
$pageTrans['content'] = $request->input('content_' . $language->code);
$pageTrans->save(); // Eloquent
}
return redirect(route('pages.index'));
}
}
Thank you!
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') }}
How to print these type of data in laravel.I am trying to create dynamic menu and these type of problem occurs.Code is like this. my code is like this.
In view composer.
public function compose(View $view)
{
$menus = $this->menu->getDynamicMenus();
$user_role = $this->role->lists('name', 'id');
//dd($user_role);
$view->with('user_role', $user_role)->with('menus', $menus);
}
menurepository code.
public function getDynamicMenus()
{
$user = $this->auth->user();
$roles = $user->roles;
// dd($roles);
$menus = [];
foreach ($roles as $role) {
//dd($role);
foreach ($role->menus as $menu) {
if ($menu["parent_id"] > 0) {
$menus[$menu["parent_id"]][$menu["id"]] = $menu->toArray();
} else {
$menus[$menu["id"]] = $menu->toArray();
}
}
}
// dd($menus);
return $menus;
}
and i print in frontend like.
#foreach($menus as $menu)
{{-- {!! Form::open() !!}
{!! Form::select('menus',$menus) !!}
{!! Form::close() !!}--}}
{{--{!! $menuitem->menu_name !!}--}}
{!! $menu->menu_url !!}
#endforeach
and it shows problem:
Trying to get property of non-object (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php) (View: E:\xampp\htdocs\basicwc\resources\views\layouts\partials\sidebar.blade.php)
as menu are getting in array like in image.
any help??
i tried to do like:
{!! menu($menus) !!}
but it says undefined problem.
I added another menu and it's structure is like this:
Access it like an array:
#foreach($menus as $menu)
...
{{ $menu['menu_name'] }}
{{ $menu['menu_url'] }}
#endforeach
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.
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