Skip to content

Instantly share code, notes, and snippets.

@essemme
Last active June 15, 2017 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save essemme/76da6e6dd1caabce591cfe50ce81adf9 to your computer and use it in GitHub Desktop.
Save essemme/76da6e6dd1caabce591cfe50ce81adf9 to your computer and use it in GitHub Desktop.
Gists for post "Saving time with a CRUD generator for Laravel" on my blog https://stefanomanfredini.info/en/2017/06/saving-time-crud-generator-laravel/
<?php
namespace [% namespace %];
use Session;
[% use_command_placeholder %]
use Illuminate\Support\Str;
class [% controller_name %] [% controller_extends %]
{
protected $[% model_name %]; // Model Instance
[% constructor %]
/**
* Display a listing of the [% model_name_plural %] .
*
* @return Illuminate\View\View
*/
public function index(Request $request)
{
$[% model_name_plural %] = [% model_name_class %]::[% with_relations_for_index %]
search($request->get('s'))
->type('parameter', $request->get('parameter'))
->orderBy($request->get('o','id'),$request->get('d','desc'))
->paginate([% models_per_page %]);
Session::flash('backUrl', $request->fullUrl());
return view('[% index_view_name %]'[% view_variables_for_index %]);
}
/**
* Show the form for creating a new {{modelName}}.
*
* @return Illuminate\View\View
*/
public function create()
{
[% relation_collections %]
if (Session::has('backUrl')) { Session::keep('backUrl');}
return view('[% create_view_name %]'[% view_variables_for_create %]);
}
/**
* Store a new [% model_name %] in the storage.
*
* @param [% request_fullname %][% request_variable %]
*
* @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
*/
public function store([% type_hinted_request_name %])
{
[% call_affirm %]
$[% data_variable %] = [% call_get_data %]; //$this->getRequestsData($request);
[% on_store_setter %]
$this->[% model_name %] = [% model_name_class %]::create( $[% data_variable %] );
$[% data_variable %] = $this->requestDataTranslateOrNew ( $[% data_variable %] );
$this->[% model_name %]->update($[% data_variable %]);
Session::flash('success_message', _i('[% model_name_class %] was added!') );
Session::has ( 'backUrl' ) ? $url = Session::get('backUrl') : $url = route('[% index_route_name %]');
return redirect($url);
}
/**
* Display the specified [% model_name %].
*
* @param int $id
*
* @return Illuminate\View\View
*/
public function show($id, Request $request)
{
$[% model_name %] = [% model_name_class %]::[% with_relations_for_show %]findOrFail($id);
Session::flash('backUrl', $request->fullUrl());
return view('[% show_view_name %]'[% view_variables_for_show %]);
}
/**
* Show the form for editing the specified [% model_name %].
*
* @param int $id
*
* @return Illuminate\View\View
*/
public function edit($id)
{
$[% model_name %] = [% model_name_class %]::findOrFail($id);
[% relation_collections %]
if (Session::has('backUrl')) { Session::keep('backUrl'); }
return view('[% edit_view_name %]'[% view_variables_for_edit %]);
}
/**
* Update the specified [% model_name %] in the storage.
*
* @param int $id
* @param [% request_fullname %][% request_variable %]
*
* @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
*/
public function update($id, [% type_hinted_request_name %])
{
[% call_affirm %]
$[% data_variable %] = [% call_get_data %]; //$this->getRequestsData($request);
[% on_update_setter %]
$this->[% model_name %] = [% model_name_class %]::findOrFail($id);
$[% data_variable %] = $this->requestDataTranslateOrNew($[% data_variable %] );
$this->[% model_name %]->update($[% data_variable %] );
Session::flash('success_message', _i('[% model_name_class %] was updated!'));
Session::has ( 'backUrl' ) ? $url = Session::get('backUrl') : $url = route('[% index_route_name %]');
return redirect($url);
}
/**
* Remove the specified [% model_name %] from the storage.
*
* @param int $id
*
* @return Illuminate\Http\RedirectResponse | Illuminate\Routing\Redirector
*/
public function destroy($id)
{
$[% model_name %] = [% model_name_class %]::findOrFail($id);
$[% model_name %]->delete();
Session::flash('success_message', _i('[% model_name_class %] was deleted!') );
Session::has ( 'backUrl' ) ? $url = Session::get('backUrl') : $url = route('[% index_route_name %]');
return redirect($url);
}
[% affirm_method %]
[% get_data_method %]
[% upload_method %]
protected function getTraslatedRequestData(Request $request, $data ) {
foreach (config('app.app_languages') as $locale) {
foreach ([% model_name_class %]::$translatedFields as $field) {
$data[$field .'-'.$locale] = !empty($request->input($field .'-'.$locale)) ? $request->input($field .'-'.$locale) : null;
//repeat with other translatable fields
}
}
return $data;
}
protected function requestDataTranslateOrNew( $data ) {
foreach (config('app.app_languages') as $locale => $language) {
foreach ($this->[% model_name %]->translatedAttributes as $field) {
if(!is_null($data["$field-{$locale}"])) {
$this->[% model_name %]->translateOrNew ( $locale )->{$field} = $data["$field-{$locale}"];
}
//repeat for other translatable fields
}
}
return $data;
}
}
<?php
//form-request.stub
namespace [% app_name %]\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class [% form_request_class %] extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function prepareForValidation ()
{
$data = $this->all ();
//Alter the field values as needed, i.e. $data['whatever'] = ..
//$data['slug_en'] = !empty($this->input('slug_en')) ? $this->input('slug_en') : Str::slug($data['title_en']);
$this->replace ($data);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
[% validation_rules %]
];
}
[% get_data_method %]
[% upload_method %]
}
//index.blade.stub
@extends('adminlte::page')
@section('title')
{{ isset([% model_header %]) ? [% model_header %] : _i("[% model_name_plural_cap %]") }}
@endsection
@section('content_header')
{{ isset([% model_header %]) ? [% model_header %] : _i("[% model_name_plural_cap %]") }}
@endsection
@section('css')
@if(config('adminlte.plugins.datatables'))
<!-- DataTables -->
<link rel="stylesheet" href="//cdn.datatables.net/v/bs/dt-1.10.13/datatables.min.css">
@endif
@endsection
@section('js')
@if(config('adminlte.plugins.datatables'))
<!-- DataTables -->
<script src="//cdn.datatables.net/v/bs/dt-1.10.13/datatables.min.js"></script>
@endif
@endsection
@section('content')
//[..]
@endsection
//From index.blade.stub
<table class="table table-striped ">
<thead>
<tr>
[% header_cells %]
@include('admin.partials.single_field_translation_index_header')
<th></th>
</tr>
</thead>
<tbody>
@foreach($[% model_name_plural %] as $[% model_name %])
<tr>
[% body_cells %]
@include( 'admin.partials.single_field_translation_index_cell', ['current_model' => $[% model_name %], 'field' => 'name'] )
// index.header.cell.blade.php
// (add sorting feature to table headers)
<th><a href="{!! Request::fullUrlWithQuery ( [ 'o' => '[% field_name %]', 'd' => 'asc' ] ) !!}">{{ _i("[% field_title %]") }}</a></th>
// views/admin/partials/single_field_translation_index_header.blade.php
@foreach(config( 'app.app_languages' ) as $code => $lang)
<th><img src="/images/flags/{{ $code }}.png" alt="{{ strtoupper($code) }}"></th>
@endforeach
// views/admin/partials/single_field_translation_index_cell.blade.php
@foreach(config( 'app.app_languages' ) as $code => $lang)
<td>
@if($current_model->hasTranslation($code))
{{ $current_model->translate($code)->{$field} }}
@endif
</td>
@endforeach
//form.blade.stub
[% form_fields_html %]
{{--Keep one of the following--}}
@include('admin.partials.single_field_translation_form_text_input', ['current_model' => isset($[% model_name %]) ? $[% model_name %] : null, 'field' => 'name'])
@include('admin.partials.multiple_fields_translation_form_text_input_tabs',
['current_model' => isset($[% model_name %]) ? $[% model_name %] : null,
'translatable_fields' => \App\Models\[% model_name_class %]::$translatedFields]
)
// views/admin/partials/multiple_fields_translation_form_text_input_tabs.blade.php
// (tabs for showing single language translation fields in a form).
// Whether fields are strings or texts is specified in a config file)
<div class="col-sm-8 col-sm-offset-2">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<?php $count = 0; ?>
@foreach(config( 'app.app_languages' ) as $code => $lang)
<li class="@if(!$count)active @endif">
<a href="#tab_{{ $code }}" data-toggle="tab" aria-expanded="@if(!$count++) true @else false @endif">
<img src="/images/flags/{{ $code }}.png"> {{ $code }}
</a>
</li>
@endforeach
</ul>
<div class="tab-content">
<?php $count = 0; ?>
@foreach(config( 'app.app_languages' ) as $code => $lang)
<div class="tab-pane @if(!$count++)active @endif" id="tab_{{ $code }}">
<h4> {{ _i($lang) }} </h4>
@foreach($translatable_fields as $field)
@if( !in_array ( $field, config ('enums.textarea_fields') ) )
<div class="form-group">
<label for="{{$field}}-{{ $code }}" class="control-label col-md-2 col-sm-2 col-xs-12">
{{ _i( \Illuminate\Support\Str::studly($field) ) }} <img src="/images/flags/{{ $code }}.png">
</label>
<div class="col-md-10 col-sm-10 col-xs-12">
<input id="{{$field}}-{{ $code }}" class="form-control col-md-7 col-xs-12" name="{{$field}}-{{ $code }}" type="text" value="{{ old($field.'-'.$code, isset($current_model) && isset($current_model->translate($code)->{$field}) ? $current_model->translate($code)->{$field} : null) }}">
</div>
</div>
@else
<div class="form-group">
<label for="{{$field}}-{{ $code }}" class="control-label col-md-2 col-sm-2 col-xs-12">
{{ _i( \Illuminate\Support\Str::studly($field) ) }} <img src="/images/flags/{{ $code }}.png">
</label>
<div class="col-md-10 col-sm-10 col-xs-12">
<textarea class="form-control editor" name="{{ $field }}-{{ $code }}" cols="50" rows="10" id="{{ $field }}-{{ $code }}" placeholder="Description">{{ isset($current_model) && isset($current_model->translate($code)->{$field}) ? $current_model->translate($code)->{$field} : null }}</textarea>
</div>
</div>
@endif
@endforeach
</div>
@endforeach
</div>
</div>
</div>
// views/admin/partials/single_field_translation_form_text_input.blade.php
@foreach(config( 'app.app_languages' ) as $code => $lang)
<div class="form-group">
<label for="{{$field}}-{{ $code }}" class="control-label col-md-2 col-sm-2 col-xs-12">
{{ _i( \Illuminate\Support\Str::studly($field) ) }} {{ _i($lang) }} <img src="/images/flags/{{ $code }}.png">
</label>
<div class="col-md-10 col-sm-10 col-xs-12">
<input id="{{$field}}-{{ $code }}" class="form-control col-md-7 col-xs-12" name="{{$field}}-{{ $code }}" type="text" value="{{ old($field.'-'.$code, isset($current_model) && isset($current_model->translate($code)->name) ? $current_model->translate($code)->name : null) }}">
</div>
</div>
@endforeach
// in show.blade.stub
<div class="panel-body">
<dl class="dl-horizontal">
[% table_rows %]
{{--Keep one of the following--}}
@include('admin.partials.single_field_translation_show', ['current_model' => isset($[% model_name %]) ? $[% model_name %] : null, 'field_label' => 'Name', 'field' => 'name'])
@include('admin.partials.multiple_fields_translation_show', ['current_model' => isset($[% model_name %]) ? $[% model_name %] : null, 'translatable_fields' => \App\Models\[% model_name_class %]::$translatedFields ] )
</dl>
</div>
// views/admin/partials/single_field_translation_show.blade.php
@foreach(config( 'app.app_languages' ) as $code => $lang)
<dt>{{ _i($field_label) }} {{ _i($lang) }} <img src="/images/flags/{{ $code }}.png"></dt>
<dd>{{ isset($current_model) && isset($current_model->translate($code)->{$field}) ? $current_model->translate($code)->{$field} : null }}</dd>
@endforeach
// views/admin/partials/multiple_fields_translation_show.blade.php
<div class="col-sm-10">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<?php $count = 0; ?>
@foreach(config( 'app.app_languages' ) as $code => $lang)
<li class="@if(!$count)active @endif">
<a href="#tab_{{ $code }}" data-toggle="tab" aria-expanded="@if(!$count++) true @else false @endif">
<img src="/images/flags/{{ $code }}.png"> {{ $code }}
</a>
</li>
@endforeach
</ul>
<div class="tab-content">
<?php $count = 0; ?>
@foreach(config( 'app.app_languages' ) as $code => $lang)
<div class="tab-pane @if(!$count++)active @endif" id="tab_{{ $code }}">
<h4> {{ _i($lang) }} </h4>
@foreach($translatable_fields as $field_label => $field)
<dt>{{ _i($field_label) }} <img src="/images/flags/{{ $code }}.png"></dt>
@if( !in_array ( $field, config('enums.textarea_fields')))
<dd>{{ isset($current_model) && isset($current_model->translate($code)->$field) ? $current_model->translate($code)->$field : null }}</dd>
@else
<dd>{!! isset($current_model) && isset($current_model->translate($code)->$field) ? $current_model->translate($code)->$field : null !!}</dd>
@endif
@endforeach
</div>
@endforeach
</div>
</div>
</div>
<?php
//extract from model.stub
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
[% use_soft_delete %]
class [% model_name_class %] extends Model
{
use Translatable;
[% use_soft_delete_trait %]
[% time_stamps %]
/**
* The database table used by the model.
*
* @var string
*/
protected $table = '[% table %]';
[% primary_key %]
/**
* Attributes that should be mass-assignable.
*
* @var array
*/
protected $fillable = [% fillable %];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [% dates %];
/**
* Property for Translatable - list of tranlsated fields
*
* @var array
*/
public $translatedAttributes = ['name',];
/**
* Static list of translatable fields (usually the same
* as $translatedAttributes) for use in Controller before
* instantiating the model
*
* @var array
*/
public static $translatedFields = ['Name' =>'name'];
/**
* The relations to eager load on every query.
*
* @var array
*/
// (optionally)
protected $with = ['translations'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment