Laravel 5.3 - Image validation not working - php

I have a problem with the validation of images or mimes overall.
This is my code:
$this->validate($request, [
'title' => 'required|max:50',
'content' => 'required|min:20',
'description' => 'required|max:140',
'file' => 'image'
]);
When I try to upload any file I get the error:
The file failed to upload.
When I dont have the image flag, everthing just works fine.
I can put things like required or max:5000.
I looked at the documentation and it should work, but it doesn't.
So what am I doing wrong?
EDIT:
Added form:
{!! Form::open(['method' => 'POST', 'action' => 'PostController#store', 'files' => 'true' ]) !!}
<div class="form-group">
{!! Form::label('title', 'Title:') !!}<br>
{!! Form::text('title', null, ['class' => 'form-control']) !!}
<small>Max 50 characters</small>
<br>
{!! Form::label('description', 'Description:') !!}<br>
{!! Form::textarea('description', null, ['class' => 'form-control', 'rows' => 2, 'cols' => 50]) !!}
<small>Max 140 characters</small>
<br>
{!! Form::label('content', 'Content:') !!}<br>
{!! Form::textarea('content', null, ['class' => 'form-control', 'id' =>'content', 'rows' => 8, 'cols' => 50]) !!}
<br>
{!! Form::label('file', 'Upload a thumbnail here:') !!} <br>
{!! Form::file('file', null, ['class' => 'form-control']) !!} <br>
<small>Only jpeg, png, bmp, gif, or svg</small>
</div>
{!! Form::submit(null, ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
EDIT 2:
added html:
<form method="POST" action="https://blog.luukwuijster.eu" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="N72xyc8mmbdFGrS78sdhIqh25awN30AboL9ecqGm">
<div class="form-group">
<label for="title">Title:</label><br>
<input class="form-control" name="title" type="text" id="title">
<small>Max 50 characters</small>
<br>
<label for="description">Description:</label><br>
<textarea class="form-control" rows="2" cols="50" name="description" id="description"></textarea>
<small>Max 140 characters</small>
<br>
<label for="content">Content:</label><br>
<textarea class="form-control" id="content" rows="8" cols="50" name="content" style="display: none;"></textarea>
<br>
<label for="file">Upload a thumbnail here:</label> <br>
<input name="file" type="file" id="file"> <br>
<small>Only jpeg, png, bmp, gif, or svg</small>
</div>
<input class="btn btn-primary" type="submit">
</form>
EDIT 3:
added the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\User;
use Illuminate\Support\Facades\Auth;
use GrahamCampbell\Markdown\Facades\Markdown;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth')->except('index', 'show');
}
public function index()
{
$posts = Post::latest()->get();
return view('welcome', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
$file = $request->file('file');
if($file){
$name = rand(1, 1000000000).'_'.$file->getClientOriginalName();
$file->move('images', $name);
$input['thumbnail'] = $name;
}else{
$input['thumbnail'] = "No_Image.png";
}
//TODO: validatie voor de thumbnails.
$this->validate($request->all(), [
'title' => 'required|max:50',
'content' => 'required|min:20',
'description' => 'required|max:140',
'file' => 'image'
]);
Auth::user()->post()->create($input);
return redirect('/');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::findOrFail($id);
$content = Markdown::convertToHtml($post->content);
return view('post', compact('post', 'content'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Auth::user()->post()->findOrFail($id);
return view('edit', compact('post'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = $request->all();
$file = $request->file('file');
if($file){
$name = rand(1, 1000000000).'_'.$file->getClientOriginalName();
$file->move('images', $name);
$input['thumbnail'] = $name;
}
//TODO: validatie voor de thumbnails.
$this->validate($request, [
'title' => 'required|max:50',
'content' => 'required|min:20',
'description' => 'required|max:140',
'file' => 'image'
]);
Auth::user()->post()->findOrFail($id)->update($input);
return redirect('/home');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
Auth::user()->post()->withTrashed()->findOrFail($id)->forceDelete();
return redirect('/recyclebin');
}
public function restore($id)
{
Auth::user()->post()->withTrashed()->findOrFail($id)->restore();
return redirect('/home');
}
public function recyclebin()
{
$posts = Post::onlyTrashed()->get();
return view('recyclebin', compact('posts'));
}
public function remove($id){
//Post::findOrFail($id)->delete();
Auth::user()->post()->findOrFail($id)->delete();
return redirect('/home');
}
}

In your opening form tag add this:
enctype="multipart/form-data"
and in the file input(where you actually upload it), add this:
multiple="multiple"
Edit:
In every form you should use the csrf_field() method. add also just befor the openning form tag.
2019 update:
You can add the #csrf directive instead of csrf_field() method. It's the same, just more convenient for some people.
Hope this helps you.

Try changing you controller like this --
public function store(Request $request) {
$this->validate($request, [
'title' => 'required|max:50',
'content' => 'required|min:20',
'description' => 'required|max:140',
'file' => 'image'
]);
$input = $request->all();
$file = $request->file('file');
if($request->hasFile('file')){
$name = rand(1, 1000000000).'_'.$file->getClientOriginalName();
$file->move('images', $name);
$input['thumbnail'] = $name;
}else{
$input['thumbnail'] = "No_Image.png";
}
Auth::user()->post()->create($input);
return redirect('/');
}
And changing 'files' => 'true' to 'files' => true

This is my code
$validator = Validator::make($input, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
])
if ($validator - > fails()) {
return $this - > sendError('Validation Error.', $validator - > errors());
}

Related

Laravel Soft Deletes dosent work in one table

I am trying to make soft deletes in my DB tables but it fails in one table. I made same things with other tables but only in one it dosen't work. When i click delete in view it deletes row in data base. I will show code of soft delete for this table and have hope that you will help me.
This is my migration for it:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->string('name')->nullable();
$table->string('PKWIU')->nullable();
$table->string('quantity')->nullable();
$table->string('unit')->nullable();
$table->string('netunit')->nullable();
$table->string('nettotal')->nullable();
$table->string('VATrate')->nullable();
$table->string('grossunit')->nullable();
$table->string('grosstotal')->nullable();
$table->timestamps();
$table->time('deleted_at')->nullable();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('form_id')
->references('id')
->on('forms')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')
->on('currencys')
->onDelete('cascade');
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
This is model for invoice. Invoice.php
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use SoftDeletes;
use Sortable;
protected $table = 'invoices';
protected $fillable = [
'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod',
'paymentdate', 'status', 'comments', 'city', 'paid', 'autonumber', 'automonth', 'autoyear', 'name',
'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
];
public $sortable = [ 'invoicenumber', 'invoicedate', 'id', 'selldate',
'user_id', 'paymentmethod', 'paymentdate', 'status', 'comments', 'grosstotal', 'nettotal', 'form_id', 'currency_id',];
protected $dates = ['deleted_at'];
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo('App\User');
}
public function form()
{
return $this->hasOne('App\Form');
}
public function currency()
{
return $this->hasOne('App\Currency');
}
public function proform()
{
return $this->belongsTo('App\Proform');
}
}
InvoiceController.php
<?php
namespace App\Http\Controllers;
use Kyslik\ColumnSortable\Sortable;
use App\Invoice;
use Illuminate\Http\Request;
use App\User;
use App\Proform;
use App\Form;
use App\Currency;
use DB;
class InvoiceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
function __construct()
{
$this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
$this->middleware('permission:product-create', ['only' => ['create','store']]);
$this->middleware('permission:product-edit', ['only' => ['edit','update']]);
$this->middleware('permission:product-delete', ['only' => ['destroy']]);
}
public function search4(Request $request)
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
$query = DB::table('users')
->join('invoices', 'users.id', '=', 'invoices.user_id');
$search = $request->get('search');
$requestData = ['showname'];
/* $query = Proform::query(); */
foreach ($requestData as $field){
$query->orWhere($field, 'like', '%'.$search.'%');
}
$data2=$query->paginate(5);
return view('invoices.index', ['invoices' => $data2, 'user'=> $user])->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
return view('invoices.index',compact('invoices', 'user'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{ $users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.create')->with('users', $users, 'forms', 'currencys');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
Invoice::create($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Invoice $invoice)
{
return view('invoices.show',compact('invoice'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Invoice $invoice)
{
$users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.edit',compact('invoice', 'users', 'forms', 'currencys'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Invoice $invoice)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
$invoice->update($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Invoice $invoice)
{
$invoice->delete();
return redirect()->route('invoices.index')
->with('success','Invoice deleted successfully');
}
}
Routes:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return view('welcome');
});
Route::get('home');
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function () {
Route::get('/search', 'UserController#search');
Route::get('/search2', 'ProductController#search2');
Route::get('/search3', 'ProformController#search3');
Route::get('/search4', 'InvoiceController#search4');
Route::post('/duplicate', 'ProformController#duplicate')->name('proforms.duplicate');
Route::get('data', 'UserController#index');
Route::get('posts', 'PostController#index');
Route::get('/prodview', 'TestController#prodfunct');
Route::resource('roles', 'RoleController');
Route::resource('users', 'UserController');
Route::resource('permissions', 'PermissionController');
Route::resource('products', 'ProductController');
Route::resource('invoices', 'InvoiceController');
Route::resource('category', 'CategoryController');
Route::resource('invoices', 'InvoiceController');
Route::resource('proforms', 'ProformController');
});
View:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie fakturami</h2>
</div>
<div class="col-md-4">
<form action="/search4" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('invoices.create') }}"> Utwórz nową fakturę</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('invoicnumber', 'Numer faktury')</th>
<th scope="col">#sortablelink('invoicedate', 'Data wystawienia')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('selldate', 'Data sprzedaży')</th>
<th scope="col">#sortablelink('paymentdate', 'Termin płatności')</th>
<th scope="col">#sortablelink('status', 'Status')</th>
<th scope="col">#sortablelink('nettotal', 'Netto razem')</th>
<th scope="col">#sortablelink('grosstotal', 'Brutto razem')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($invoices as $invoice)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $invoice->invoicenumber }}</td>
<td>{{ $invoice->invoicedate }}</td>
<td>{{ $invoice->user->showname ?? $invoice->showname }}</td>
<td>{{ $invoice->selldate }}</td>
<td>{{ $invoice->paymentdate }}</td>
<td>{{ $invoice->status }}</td>
<td>{{ $invoice->nettotal }}</td>
<td>{{ $invoice->grosstotal }}</td>
<td>
<form action="{{ route('invoices.destroy',$invoice->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('invoices.show',$invoice->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('invoices.edit',$invoice->id) }}">Edytuj</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $invoices ?? ''->appends(request()->except('page'))->render() !!}
<p class="text-center text-primary"><small>ARTplus 2020</small></p>
#endsection
You must to use $table->softDeletes(); instead of $table->time('deleted_at')->nullable();.
softDeletes() method used timestamp instead of time format date. Maybe it will solve your problem;

Cakephp3 Upload Thumbnail generation with Josegonzalez/Upload.Upload

I am trying to get Josegonzalez/Upload.Upload to work. I have a working page for uploading Audio, but I am trying to make an image gallery with thumbnail generation. Upon submitting my image, I am redirected to the add page with the error "The provided value is invalid
The provided value is invalid" twice below the file upload form. I have attached my ArtworkTable.php and my view for add.
I have tried renaming things, ->AllowEmpty, and adding some database stuff.
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Artwork Model
*
* #method \App\Model\Entity\Artwork get($primaryKey, $options = [])
* #method \App\Model\Entity\Artwork newEntity($data = null, array $options = [])
* #method \App\Model\Entity\Artwork[] newEntities(array $data, array $options = [])
* #method \App\Model\Entity\Artwork|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
* #method \App\Model\Entity\Artwork saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* #method \App\Model\Entity\Artwork patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* #method \App\Model\Entity\Artwork[] patchEntities($entities, array $data, array $options = [])
* #method \App\Model\Entity\Artwork findOrCreate($search, callable $callback = null, $options = [])
*/
class ArtworkTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('artwork');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->getValidator()->allowEmpty('image')->allowEmpty('thumb');
$this->addBehavior('Josegonzalez/Upload.Upload', [
'image' => [
'fields' => [
'dir' => 'image_dir',
'size' => 'image_size',
'type' => 'image_type'
],
'nameCallback' => function ($table, $entity, $data, $field, $settings) {
return strtolower($data['name']);
},
'transformer' => function ($table, $entity, $data, $field, $settings) {
$extension = pathinfo($data['name'], PATHINFO_EXTENSION);
// Store the thumbnail in a temporary file
$tmp = tempnam(sys_get_temp_dir(), 'upload') . '.' . $extension;
// Use the Imagine library to DO THE THING
$size = new \Imagine\Image\Box(40, 40);
$mode = \Imagine\Image\ImageInterface::THUMBNAIL_INSET;
$imagine = new \Imagine\Gd\Imagine();
// Save that modified file to our temp file
$imagine->open($data['tmp_name'])
->thumbnail($size, $mode)
->save($tmp);
// Now return the original *and* the thumbnail
return [
$data['tmp_name'] => $data['name'],
$tmp => 'thumbnail-' . $data['name'],
];
},
'deleteCallback' => function ($path, $entity, $field, $settings) {
// When deleting the entity, both the original and the thumbnail will be removed
// when keepFilesOnDelete is set to false
return [
$path . $entity->{$field},
$path . 'thumbnail-' . $entity->{$field}
];
},
'keepFilesOnDelete' => false
]
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmptyString('id', null, 'create');
$validator
->scalar('image')
->maxLength('image', 255)
->requirePresence('image', 'create')
->notEmptyFile('image');
$validator
->scalar('thumb')
->maxLength('thumb', 255)
->allowEmpty('thumb');
$validator
->scalar('title')
->maxLength('title', 255)
->requirePresence('title', 'create')
->notEmptyString('title');
$validator
->scalar('description')
->requirePresence('description', 'create')
->notEmptyString('description');
return $validator;
}
}
View for add.ctp
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Artwork $artwork
*/
?>
<nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('List Artwork'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="artwork form large-9 medium-8 columns content">
<fieldset>
<legend><?= __('Add Artwork') ?></legend>
<?= $this->Form->create($artwork, ['type' => 'file']); ?>
<?= $this->Form->control('title'); ?>
<?= $this->Form->control('image', ['type' => 'file']); ?>
<?= $this->Form->control('description'); ?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</fieldset>
</div>

Form doesn't get submitted in yii2

I'm using yii2 advanced app and im stuck at a point where my form doesn't get submitted. It refreshes and stays on the same page. There are no errors shown too.
Here is the model code Countries.php
<?php
namespace backend\models\base;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use mootensai\behaviors\UUIDBehavior;
/**
* This is the base model class for table "countries".
*
* #property integer $id
* #property string $sortname
* #property string $name
* #property integer $phonecode
* #property integer $created_at
* #property integer $updated_at
* #property integer $created_by
* #property integer $updated_by
* #property integer $deleted_at
* #property integer $deleted_by
*
* #property \backend\models\States[] $states
*/
class Countries extends \yii\db\ActiveRecord
{
use \mootensai\relation\RelationTrait;
private $_rt_softdelete;
private $_rt_softrestore;
public function __construct(){
parent::__construct();
$this->_rt_softdelete = [
'deleted_by' => \Yii::$app->user->id,
'deleted_at' => date('Y-m-d H:i:s'),
];
$this->_rt_softrestore = [
'deleted_by' => 0,
'deleted_at' => date('Y-m-d H:i:s'),
];
}
/**
* This function helps \mootensai\relation\RelationTrait runs faster
* #return array relation names of this model
*/
public function relationNames()
{
return [
'states'
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['sortname', 'name', 'phonecode'], 'required'],
[['phonecode', 'created_at', 'updated_at', 'created_by', 'updated_by', 'deleted_at', 'deleted_by'], 'integer'],
[['sortname'], 'string', 'max' => 3],
[['name'], 'string', 'max' => 150],
[['lock'], 'default', 'value' => '0'],
[['lock'], 'mootensai\components\OptimisticLockValidator']
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'countries';
}
/**
*
* #return string
* overwrite function optimisticLock
* return string name of field are used to stored optimistic lock
*
*/
public function optimisticLock() {
return 'lock';
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'sortname' => Yii::t('app', 'Sortname'),
'name' => Yii::t('app', 'Name'),
'phonecode' => Yii::t('app', 'Phonecode'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getStates()
{
return $this->hasMany(\backend\models\States::className(), ['country_id' => 'id']);
}
/**
* #inheritdoc
* #return array mixed
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => new \yii\db\Expression('NOW()'),
],
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
'uuid' => [
'class' => UUIDBehavior::className(),
'column' => 'id',
],
];
}
/**
* #inheritdoc
* #return \backend\models\query\CountriesQuery the active query used by this AR class.
*/
public static function find()
{
$query = new \backend\models\query\CountriesQuery(get_called_class());
return $query->where(['countries.deleted_by' => 0]);
}
}
And the controller CountriesController.php
<?php
namespace backend\controllers;
use Yii;
use backend\models\Countries;
use backend\models\search\CountriesSearch;
use backend\controllers\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CountriesController implements the CRUD actions for Countries model.
*/
class CountriesController extends BackendController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
'roles' => ['admin']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Countries models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CountriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Countries model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerStates' => $providerStates,
]);
}
/**
* Creates a new Countries model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Countries();
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Countries model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Countries();
}else{
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Countries model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Countries information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerStates' => $providerStates,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Countries model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param mixed $id
* #return mixed
*/
public function actionSaveAsNew($id) {
$model = new Countries();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Countries model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Countries the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Countries::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for States
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddStates()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('States');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formStates', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
and the view file create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model backend\models\Apps */
$this->title = Yii::t('app', 'Create Apps');
?>
<div class="uk-container uk-container-small uk-position-relative">
<div><!----> <div>
<h1 id="navbar" class="uk-h2 tm-heading-fragment">
Apps
</h1>
<!-- Start Breadcrumb -->
<ul class="uk-breadcrumb">
<li><?= Html::a('Admin', ['/'])?></li>
<li><?= Html::a('Apps', ['/apps'])?></li>
<li>Create</li>
</ul>
<!-- End Breadcrumb -->
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
and view _form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use alexeevdv\widget\SluggableInputWidget;
use dosamigos\ckeditor\CKEditor;
/* #var $this yii\web\View */
/* #var $model backend\models\Apps */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="uk-margin-auto">
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true, 'placeholder' => 'Title']) ?>
<?= $form->field($model, 'slug')->widget(SluggableInputWidget::className(), [
'dependsOn' => 'title',
]); ?>
<?= $form->field($model, 'content')->widget(CKEditor::className(), [
'options' => ['rows' => 6],
'preset' => 'basic',
'clientOptions' => [
'filebrowserImageBrowseUrl' => yii\helpers\Url::to(['imagemanager/manager', 'view-mode'=>'iframe', 'select-type'=>'ckeditor']),
]
]);?>
<?= $form->field($model, 'video')->textInput(['maxlength' => true, 'placeholder' => 'Video']) ?>
<?= $form->field($model, 'category')->widget(\kartik\widgets\Select2::classname(), [
'data' => \yii\helpers\ArrayHelper::map(\backend\models\Categories::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
'options' => ['placeholder' => Yii::t('app', 'Choose a category')],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'status')->textInput(['placeholder' => 'Status']) ?>
<div class="form-group">
<?php if(Yii::$app->controller->action->id != 'save-as-new'): ?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn uk-button uk-button-primary' : 'btn uk-button uk-button-primary']) ?>
<?php endif; ?>
<?php if(Yii::$app->controller->action->id != 'create'): ?>
<?= Html::submitButton(Yii::t('app', 'Save As New'), ['class' => 'btn uk-button uk-button-default', 'value' => '1', 'name' => '_asnew']) ?>
<?php endif; ?>
<?= Html::a(Yii::t('app', 'Cancel'), Yii::$app->request->referrer , ['class'=> 'btn uk-button uk-button-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I've browsed few articles, but of no help. My form has a <?php ActiveForm::end(); ?> at the end of the form. I also tried to remove the select2 widget but i still get the same issue. Could someone help me out why this is happening?
Html output rendered of create.php
<div class="uk-container uk-container-small uk-position-relative">
<div><!----> <div>
<h1 id="navbar" class="uk-h2 tm-heading-fragment">
Countries
</h1>
<!-- Start Breadcrumb -->
<ul class="uk-breadcrumb">
<li>Admin</li>
<li>Countries</li>
<li>Create</li>
</ul>
<!-- End Breadcrumb -->
<div class="uk-margin-auto">
<form id="w0" action="/final/backend/en-us/countries/create" method="post">
<input type="hidden" name="_csrf" value="zIvM0awWY3XpcrF1kY6gFY00ghnL1cgwTYhaEqF7RO2hch4x5AznMwtfWxWp4D-YW9yJy5aiNupb0JnMSbi5qQ==">
<div class="error-summary" style="display:none"><p>Please fix the following errors:</p><ul></ul></div>
<div class="form-group field-countries-id">
<input type="text" id="countries-id" class="form-control" name="Countries[id]" style="display:none">
</div>
<div class="form-group field-countries-sortname required">
<label class="control-label" for="countries-sortname">Sortname</label>
<input type="text" id="countries-sortname" class="form-control" name="Countries[sortname]" maxlength="3" placeholder="Sortname" aria-required="true">
<div class="help-block"></div>
</div>
<div class="form-group field-countries-name required">
<label class="control-label" for="countries-name">Name</label>
<input type="text" id="countries-name" class="form-control" name="Countries[name]" maxlength="150" placeholder="Name" aria-required="true">
<div class="help-block"></div>
</div>
<div class="form-group field-countries-phonecode required">
<label class="control-label" for="countries-phonecode">Phonecode</label>
<input type="text" id="countries-phonecode" class="form-control" name="Countries[phonecode]" placeholder="Phonecode" aria-required="true">
<div class="help-block"></div>
</div>
<div id="w3-container" class=" tabs-above tab-align-left tabs-krajee"><ul id="w3" class="nav nav-tabs nav nav-tabs hidden-print" data-krajee-tabsx="tabsX_0b4b2adf" role="tablist"><li class="active"><i class="glyphicon glyphicon-book"></i> States</li></ul>
<div class="tab-content printable"><div class="h3 visible-print-block"><i class="glyphicon glyphicon-book"></i> States</div>
<div id="w3-tab0" class="tab-pane fade in active"><div class="form-group" id="add-states">
<div id="w1" class="grid-view hide-resize" data-krajee-grid="kvGridInit_7fee31f2"><div class="panel panel-default">
<div class="rc-handle-container" style="width: 628px;"><div class="rc-handle" style="left: 50px; height: 37px;"></div><div class="rc-handle" style="left: 496px; height: 37px;"></div></div><div id="w1-container" class="table-responsive kv-grid-container"><table class="kv-grid-table table table-hover kv-table-wrap"><thead>
<tr><th class="kv-align-center kv-align-middle" style="width: 7.96%;" data-col-seq="0">#</th><th class="kv-align-top kv-grid-hide" data-col-seq="1">Id</th><th class="kv-align-top" data-col-seq="2" style="width: 71.02%;">Name</th><th class="kv-align-middle" data-col-seq="3" style="width: 21.02%;"></th></tr>
</thead>
<tbody>
<tr><td colspan="4"><div class="empty">No results found.</div></td></tr>
</tbody></table></div>
<div class="kv-panel-after"><button type="button" class="btn btn-success kv-batch-create" onclick="addRowStates()"><i class="fa fa-plus"></i>Add States</button></div>
</div></div> </div>
</div>
</div></div> <div class="form-group">
<button type="submit" class="uk-button uk-button-primary">Create</button> <a class="uk-button uk-button-danger">Cancel</a> </div>
</form>
</div>
</div>
</div>
</div>
Changing loadAll() and saveAll() to load() and save() has solved the issue
<?php
namespace backend\controllers;
use Yii;
use backend\models\Countries;
use backend\models\search\CountriesSearch;
use backend\controllers\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CountriesController implements the CRUD actions for Countries model.
*/
class CountriesController extends BackendController
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new','add-states'],
'roles' => ['admin']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Countries models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CountriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Countries model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerStates' => $providerStates,
]);
}
/**
* Creates a new Countries model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Countries();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Countries model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Countries();
}else{
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Countries model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Countries information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerStates = new \yii\data\ArrayDataProvider([
'allModels' => $model->states,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerStates' => $providerStates,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Countries model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param mixed $id
* #return mixed
*/
public function actionSaveAsNew($id) {
$model = new Countries();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Countries model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Countries the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Countries::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for States
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddStates()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('States');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formStates', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
Thank you #aendeerei for the quick help!

Access controller return value in view laravel

I've returned a value from my controller.When I use the value in my view blade,it shows Syntax error
Here is my code,
Controller
public function edit($id)
{
$a = DB::select('select * from users where id = "$pid"', array(1));
return view('sample', ['users' => $a]);
}
And in View blade,
{!! Form::Id('Id', $value = {{$a}}, ['class' => 'form-control1', 'placeholder' => 'Id']) !!}
How 'ld I change my code,Help me
You can do it wit eloquent like this :
public function edit($id)
{
$a = User::find($id);
return view('sample', ['user' => $a]);
}
And on top of your controller add the import :
use App\User;
In the view it's user that will be seen not a so :
<input type="text" name="id" value="{{ $user->id }}" />
{!! Form::email('email', $user->email, ['class' => 'form-control1', 'placeholder' => 'email']) !!}

Trying to get property of non-object - private message laravel

Welcome ! I have a problem I try to use this https://github.com/cmgmyr/laravel-messenger Laravel package for private messaging on Laravel 5.2. When i didn't have any recipients I could post a message but when I add new user to database and recipients showed in form now I have an error : trying to get property of non -object. All controllers and views are copied from examples from link above.
Regards
Message controller :
<?php
namespace App\Http\Controllers;
use App\User;
use Carbon\Carbon;
use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Participant;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
class MessagesController extends Controller
{
/**
* Show all of the message threads to the user.
*
* #return mixed
*/
public function index()
{
$currentUserId = Auth::user()->id;
// All threads, ignore deleted/archived participants
$threads = Thread::getAllLatest()->get();
// All threads that user is participating in
// $threads = Thread::forUser($currentUserId)->latest('updated_at')->get();
// All threads that user is participating in, with new messages
// $threads = Thread::forUserWithNewMessages($currentUserId)->latest('updated_at')->get();
return view('messenger.index', compact('threads', 'currentUserId'));
}
/**
* Shows a message thread.
*
* #param $id
* #return mixed
*/
public function show($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('messages');
}
// show current user in list if not a current participant
// $users = User::whereNotIn('id', $thread->participantsUserIds())->get();
// don't show the current user in list
$userId = Auth::user()->id;
$users = User::whereNotIn('id', $thread->participantsUserIds($userId))->get();
$thread->markAsRead($userId);
return view('messenger.show', compact('thread', 'users'));
}
/**
* Creates a new message thread.
*
* #return mixed
*/
public function create()
{
$users = User::where('id', '!=', Auth::id())->get();
return view('messenger.create', compact('users'));
}
/**
* Stores a new message thread.
*
* #return mixed
*/
public function store()
{
$input = Input::all();
$thread = Thread::create(
[
'subject' => $input['subject'],
]
);
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'body' => $input['message'],
]
);
// Sender
Participant::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
'last_read' => new Carbon,
]
);
// Recipients
if (Input::has('recipients')) {
$thread->addParticipant($input['recipients']);
}
return redirect('messages');
}
/**
* Adds a new message to a current thread.
*
* #param $id
* #return mixed
*/
public function update($id)
{
try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'The thread with ID: ' . $id . ' was not found.');
return redirect('messages');
}
$thread->activateAllParticipants();
// Message
Message::create(
[
'thread_id' => $thread->id,
'user_id' => Auth::id(),
'body' => Input::get('message'),
]
);
// Add replier as a participant
$participant = Participant::firstOrCreate(
[
'thread_id' => $thread->id,
'user_id' => Auth::user()->id,
]
);
$participant->last_read = new Carbon;
$participant->save();
// Recipients
if (Input::has('recipients')) {
$thread->addParticipant(Input::get('recipients'));
}
return redirect('messages/' . $id);
}
}
Standard routes:
Route::group(['prefix' => 'messages'], function () {
Route::get('/', ['as' => 'messages', 'uses' => 'MessagesController#index']);
Route::get('/create', ['as' => 'messenger.create', 'uses' => 'MessagesController#create']);
Route::post('/', ['as' => 'messages.store', 'uses' => 'MessagesController#store']);
Route::get('{id}', ['as' => 'messages.show', 'uses' => 'MessagesController#show']);
Route::put('{id}', ['as' => 'messages.update', 'uses' => 'MessagesController#update']);
});
And standard view:
{!! Form::open(['route' => 'messages.store']) !!}
<div class="col-md-6">
<!-- Subject Form Input -->
<div class="form-group">
{!! Form::label('subject', 'Subject', ['class' => 'control-label']) !!}
{!! Form::text('subject', null, ['class' => 'form-control']) !!}
</div>
<!-- Message Form Input -->
<div class="form-group">
{!! Form::label('message', 'Message', ['class' => 'control-label']) !!}
{!! Form::textarea('message', null, ['class' => 'form-control']) !!}
</div>
#if($users->count() > 0)
<div class="checkbox">
#foreach($users as $user)
<label title="{{ $user->name }}"><input type="checkbox" name="recipients[]" value="{{ $user->id }}">{!!$user->name!!}</label>
#endforeach
</div>
#endif
<!-- Submit Form Input -->
<div class="form-group">
{!! Form::submit('Submit', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
</div>

Categories