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']) !!}
Related
I have User Role models defined in a many-to-many relationship. When creating user I have a multiple select box to pick roles for specific user:
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="roles">Roles</label>
{!! Form::select('roles[]',$roles, null,['class' => 'form-control selectpicker','multiple' => 'true']) !!}
</div>
</div>
This is a form which is shared in both create and edit methods, but for edit it is like this:
{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
#include('patients.partials.form')
{!! Form::close()!!}
When I try to edit user with roles, no roles get selected...this is the controller
public function edit(User $user)
{
$clinics = Clinic::pluck('name', 'id');
$roles = Role::pluck('display_name', 'id');
$states = State::pluck('name', 'id');
$cities = City::pluck('name', 'id');
return view('users.edit', compact('user', 'clinics', 'states', 'cities', 'roles'));
}
EDIT:
I handle update like this:
public function update(Request $request, User $user)
{
if ($request->has('password'))
$user->update($request->except('password_confirmation'));
else
$user->update($request->except('password', 'password_confirmation'));
$user->roles()->sync($request->roles);
return redirect('users')->with('status', 'User Updated!');
}
Part of the request dump:
"roles": [
"1",
"4"
],
"first_name": "xy",
"last_name": "yx",
The third parameter of the form select takes the selected array of item. Make the following changes for your selected roles to show up when you edit.
// Pass the current user roles
public function edit(User $user)
{
$userRoles = $user->roles->pluck('id');
$clinics = Clinic::pluck('name', 'id');
$roles = Role::pluck('display_name', 'id');
$states = State::pluck('name', 'id');
$cities = City::pluck('name', 'id');
return view('users.edit', compact('user', 'userRoles', 'clinics', 'states', 'cities', 'roles'));
}
// Pass the selected list of roles
{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
#include('patients.partials.form', ['selected' => $userRoles])
{!! Form::close()!!}
// Check if a selected value is given and use it. This makes it reusable with create and edit.
{!! Form::select('roles[]', $roles, isset($selected) ? $selected : null, [
'class' => 'form-control selectpicker',
'multiple' => 'true'
]) !!}
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>
I'm trying to populate the data to edit form. Here's my model
public function EditBatch($id,$request){
$data= DB::table('in_batch')
->where('id', $id)
->update(array(
'id'=>$request->input('id'),
'file_name' => $request->input('file_name'),
'batch_type' => $request->input('batch_type'),
'activity_type' => $request->input('activity_type'),
'schedule_time' => $request->input('schedule_time'),
'predecessor' => $request->input('predecessor'),
'priority' => $request->input('priority'),
'batch_remark'=>$request->input('batch_remark'),
'approved_by' => Auth::user()->id,
'approved_on'=>date("Y-m-d H:i:s"),
));
return $data;
}
here's my controller
public function edit($id){
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$batch = new ManageBatch();
$batch->GetBatchById($id);
return view('batch.edit', array('batch'=>$batch,'batch_type'=>$batch_type));
}
here's my view
{!! Form::open (array('url' => array('batch/update',$batch->id), 'class' => 'form-horizontal', 'method' => 'post','id'=>'editbatch')) !!}
<div class="form-group">
{!! Form::label('batch_id', 'batch_id',array('class'=>'col-md-4 control-label')) !!}
<div class="col-md-6">
{!! Form::text('batch_id',$batch->id,array('class'=>'form-control','id'=>'batch_id')) !!}
</div>
</div>
{!! Form::close() !!}
when i trying to load the data to the view as above error is displaying
Undefined property: App\Models\Batch\ManageBatch::$id (View: C:\wamp\www\hutch-in-portal\resources\views\batch\edit.blade.php)
how to solve this ?
thankyou
well i found a solution and the mistake was in the controller method
public function edit($id)
{
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$ouser = new ManageBatchUser();
$batch_user = $ouser->GetUserDropDown();
$batch = new ManageBatch();
$batch_details=$batch->GetBatchById($id);
return view('batch.edit',array('batch_details'=>$batch_details[0],'batch_type'=>$batch_type,'batch_user'=>$batch_user));
}
since i'm passing a single row to the view . i must add the index [0] in return. finally it worked
UPDATED. I have one form that adds data to two different tables (Articles & Deals). An Article has many deals. A deal has one Article. There are multiple deals with different dealnames that the user inputs on the create and edit form. I can create an Article with many Deals fine, and I can populate the edit form with the data from the Deals table, but when I update my 'deals' table using the Articles Controller it just updates every 'dealname' with the last dealname that is inputted. I only need to update the 'dealname' column as all other columns will stay the same. If I remove the dealname/deals part of the form I can update fine.
How can I update the deals table correctly? I know I have to change something in the update function of my Articles Controller.
I'm using Laravel 5.
The Articles Table has: id, title, image, description, address. The Deals table has: id, dealname, article_id, dayID.
Articles Controller- Update
public function update(ArticleRequest $request, $id)
{
$article = Article::find($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->fill($request->input())->save();
//Get IDs of deals to be updated.
$dealID = Deal::all()->lists('dealname', 'id');
$dealID = $dealID->toArray();
$dealID = array_keys($dealID);
$deals = $request->input('dealname');
foreach($deals as $deal) {
Deal::whereIn('id', $dealID)->update(['dealname' => $deal]);
}
return redirect('/');
}
Form
{!! Form::model($article, ['route' => ['articleUpdate_path', $article->id], 'files' => true, 'method' => 'PATCH']) !!}
{!! Form::label('title','TITLE') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
{!! $errors->first('title','<p class="error">:message</p>')!!}
{!! Form::label('image','PHOTO') !!}
{!! Form::file('image', null, ['class' => 'form-control']) !!}
{!! Form::label('description','DESCRIPTION') !!}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
#foreach ($article->deals as $deal)
#if($deal->dayID == '1' )
{!! Form::label('dealname','Monday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '1']) !!}
#endif
#if($deal->dayID == '2' )
{!! Form::label('dealname','Tuesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '2']) !!}
#endif
#if($deal->dayID == '3' )
{!! Form::label('dealname','Wednesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '3']) !!}
#endif
#endforeach
{!! Form::label('address','ADDRESS') !!}
{!! Form::text('address', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
Articles Controller -Store
public function store(ArticleRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$article = ($request->except(['image']));
$article['image'] = $image_name;
$article = Article::create($article);
// GET INPUT
$deals = $request->input('dealname');
// GET ID OF ARTICLE
$articleID = $article->id;
// N is the day id that increments
$n = 1;
foreach($deals as $deal) {
Deal::create(['dealname' => $deal, 'article_id' => $articleID, 'dayID' => $n++]);
}
return redirect()->route('articles_path');
}
ARTICLE MODEL
class Article extends Model
{
public function deals()
{
return $this->hasMany('App\Deal');
}
protected $fillable = array('title', 'photo', 'description', 'address');
}
DEAL MODEL
class Deal extends Model
{
public function article()
{
return $this->belongsTo('App\Article')->withTimestamps();
}
protected $fillable = array('dealname', 'article_id', 'dayID');
}
I'm really not sure to fully understand your question, but would something like that could be useful in your case:
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
$article->deals->where('dayID',1)->first()->dealname = $request->input('dealname')[0];
$article->deals->where('dayID',1)->first()->save();
$article->deals->where('dayID',2)->first()->dealname = $request->input('dealname')[1];
$article->deals->where('dayID',2)->first()->save();
$article->deals->where('dayID',3)->first()->dealname = $request->input('dealname')[2];
$article->deals->where('dayID',3)->first()->save();
}
Are they only those 3 dayIds you are using in your form?
EDIT:
You could also try with a for loop. This is untested code, so you might want to optimize it :)
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
for($i = 0; $i < sizeof($request->input('dealname')); $i++) {
$article->deals->where('dayID',($i + 1))->first()->dealname = $request->input('dealname')[$i];
$article->deals->where('dayID',($i + 1))->first()->save();
}
}
Error:
Attempt to assign property of non-object; ErrorException in AdminController.php line 40:
AdminController:
public function createSlider(AdminRequest $request)
{
$input = Request::all();
Sliders::create($input);
if (Request::hasFile('image')) {
$imageName = Request::input('title'). '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image/', $imageName
);
$input->image = $imageName; //------------> line 40.......
}
$input->save();
}
Html:
{!!Form::open(array('url' => 'admin/new_slider', 'files' => true)) !!}
<div class = "form-group">
{!!Form::label('title', 'Title:', ['class' => 'control-label']) !!}
{!!Form::text('title', null, ['class'=> 'input-mini ina tch'])!!}
{!!Form::label('title', 'Description:', ['class' => 'control-label']) !!}
{!!Form::text('description', null, ['class'=> 'input-mini '])!!}
</div>
<div class = "form-group">
{!!Form::label('title', 'Link:', ['class' => 'control-label']) !!}
{!!Form::text('link', null, ['class'=> 'input-mini'])!!}
{!!Form::label('title', 'Image:', ['class' => 'control-label']) !!}
{!! Form::file('image', ['id' => 'imgInp', 'class' => 'prev-upload']) !!}
</div>
<div class = "form-group">
{!!Form::submit('Submit', ['class'=> 'btn btn-default'])!!}
</div>
{!! Form::close() !!}
I've been struggling with this all morning. I want to be able to accept a file upload along with the form information. Renaming the file is not necessary just how i thought i could get this to work. Is there a better way to do this file upload and move?
I changed the format of everything and it worked.
public function createSlider(AdminRequest $request)
{
$slider = new Sliders(array(
'title' => $request->get('title'),
'description' => $request->get('description'),
'link' => $request->get('link')
));
$slider->save();
$imageName = $slider->title .'_gin_slider'. '.' .
$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(
base_path() . '/public/assets/image', $imageName
);
$slider->image = $imageName;
$slider->save();
return redirect('/admin');
}
For further reference: the issue occurs when your controller, router or middleware method does not return a valid response. You should always return a response from your root called method, whether it's actual data or a redirect. In case of middlewares it can be the request itself via Closure.
In case of controllers it should be:
public function index()
{
return response() || redirect()->back();
}
In case of middlewares:
public function handle($request, Closure $next)
{
return $next($request) || response() || redirect()->back();
}
In case of route closures:
Route::get('foo/bar', function(){
return response() || redirect()->back();
});
|| means 'or'