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

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>

Related

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']) !!}

Model binding in registration form for Laravel 5.4

I am trying to pull list of data from database and show it as a dropdown in a registration form. But I get error undefined variable universities.
Register Controller
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'university' => $data['university'],
'school_dept' => $data['school_dept'],
])
->with(compact('universities','sch_depts'));
}
register.blade.php
<div class="form-group{{ $errors->has('university') ? ' has-error' : '' }}">
<label for="university" class="col-md-4 control-label">University</label>
<div class="col-md-6">
{!! Form::select('university', $universities, null, array('id' => 'universitiy', 'class' => 'form-control')) !!}
#if ($errors->has('university'))
<span class="help-block">
<strong>{{ $errors->first('university') }}</strong>
</span>
#endif
</div>
</div>
I am getting an error universities undefined.
Let's assume you have a controller called RegisterController, the create method should only return view and it's corresponding data.
public function create()
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return view('register', compact('universities', 'sch_depts'));
}
and you should also have a store method:
public function store(\Illuminate\Http\Request $request)
{
// your validation goes here
// or just use form request validation
// docs: https://laravel.com/docs/5.4/validation#form-request-validation
User::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password')),
'university' => $request->get('university'),
'school_dept' => $request->get('school_dept'),
]);
// login user here or redirect to success page
}
and your routes/web.php file should contain the following routes:
Route::get('register', 'RegisterController#create');
Route::post('register', 'RegisterController#store');
This is really basics of Laravel, please read the docs.
P.S. Laravel comes with great Authentication system, which you can override to your needs.
This is what I did in Laravel 7, I'm also using the default authentication implementation from Laravel, so it might help
The solution is: in the RegisterController overwrite the method showRegistrationForm (which is declared in /vendor/laravel/ui/auth-backend/RegisterUsers) and add the data array.
So you will add something like this to your RegisterController
public function showRegistrationForm()
{
$universities = University::lists('id', 'university');
$sch_depts = Department::lists('id', 'department');
return view(
'auth.register',
[
'universities' => $universities,
'sch_depts' => $sch_depts
]
);
}}

Laravel 5.3 - Image validation not working

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());
}

Laravel PHP, trying to redirect to an id

I am a beginner with php and laravel. I have recently created a form at the bottom of my website, that when you click the submit button it sends the data to an email address.
However if you don't fill it in correctly and click submit it refreshes the page and returns to the top of the page. If you submit the form correctly it goes to /contact.
What I am desperate to do is keep the page at the same point on the website (with the form on the screen) instead of refreshing the screen. Same if the form is submitted correctly I would like the screen to stay still.
Routes/web.php:
Route::get('/', 'PagesController#home');
Route::get('about', 'PagesController#about');
Route::get('contact',
['as' => 'contact', 'uses' => 'AboutController#create']);
Route::post('contact',
['as' => 'contact_store', 'uses' => 'AboutController#store']);
ContactFormRequest.php:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ContactFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'number' => 'required',
'message' => 'required',
];
}
}
AboutController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
class AboutController extends Controller
{
public function create()
{
return view('pages.contact');
}
public function store(ContactFormRequest $request)
{
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
}
contact.blade.php
<div class="one-half">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
{!! Form::open(array('route' => 'contact_store', 'class' => 'form')) !!}
<div class="form-group">
{!! Form::text('name', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your name')) !!}
</div>
<div class="form-group">
{!! Form::text('email', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your e-mail address')) !!}
</div>
<div class="form-group">
{!! Form::number('number', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your Number')) !!}
</div>
<div class="form-group">
{!! Form::text('message', null,
array('required',
'class'=>'form-control',
'placeholder'=>'Your message')) !!}
</div>
<div class="form-group">
{!! Form::submit('Contact Us!',
array('class'=>'form-button btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
I am also new to using stackoverflow, so I apologise ahead if I have missed anything or done anything incorrectly. Please let me know if you need anything more.
Can't really understand your problem, but try to add this in your store() method:
return \Redirect::back()->with('message', 'Thanks for contacting us!');
But it looks like you want to submit/validate your forms without refreshing the page, so the only solution for this is to use AJAX requests.
May be this can be something. Using the validation helper.
function store(ContactFormRequest $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'number' => 'required',
'message' => 'required',
]);
// If !$this->validate Laravel will automatic return to the previous page (the form page)
// And you can grab the errors with $errors->first('name'), $errors->first('email') etc
\Mail::send('emails.contact',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'number' => $request->get('number'),
'user_message' => $request->get('message')
), function($message)
{
$message->from('sketchsitestest#gmail.com');
$message->to('sketchsitestest#gmail.com', 'Admin')->subject('Testing');
});
return \Redirect::route('contact')->with('message', 'Thanks for contacting us!');
}
Grab the errors like this:
#if ($errors->has('message'))
<span class="help-block">
<strong>{{ $errors->first('message') }}</strong>
</span>
#endif
Here you the docs about the validation, if you are using Laravel 5.3

laravel edit and update method returning as Undefined variable on class

I'm trying to update my records in my ProjectsController, however when I try to route to the controller I am getting thrown the following error:
ErrorException
Undefined variable: project
I'm not too sure as too what I've done wrong and I'm sorry to overload you guys with code but not sure where the problem lies. Bit of a newbie with Laravel so would be great to get some help!
The function it is referring to is the following:
public function edit($id)
{
// get the project
$project = Project::find($project);
// show the edit form and pass the project
return View::make('projects.edit')
->with('project', $project);
}
My update function is as follows:
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'project_name' => 'required',
'project_brief' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('projects/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$project = Project::find($id);
$project->project_name = Input::get('project_name');
$project->project_brief = Input::get('project_brief');
$project->save();
// redirect
Session::flash('message', 'Successfully updated!');
return Redirect::to('profile');
}
}
I route to the Project Controller as follows:
Route::group(["before" => "auth"], function()
{
Route::any("project/create", [
"as" => "project/create",
"uses" => "ProjectController#create"
]);
Route::any("project/{resource}/edit", [
"as" => "project/edit",
"uses" => "ProjectController#edit"
]);
Route::any("project/index", [
"as" => "project/index",
"uses" => "ProjectController#index"
]);
Route::any("project/store", [
"as" => "project/store",
"uses" => "ProjectController#store"
]);
Route::any("project/show", [
"as" => "project/show",
"uses" => "ProjectController#show"
]);
});
My form is as follows:
<h1>Edit {{ $project->project_name }}</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::model($project, array('route' => array('projects.update', $project->id), 'method' => 'PUT')) }}
<div class="form-group">
{{ Form::label('project_name', 'Project Name') }}
{{ Form::text('project_name', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('Project Brief', 'Project Brief') }}
{{ Form::textarea('project_brief', null, array('class' => 'form-control', 'cols' => '100')) }}
</div>
{{ Form::submit('Edit the Project!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
Looks like you misplaced $project in find(), should be $id here:
public function edit($id)
{
// get the project
$project = Project::find($id);
// show the edit form and pass the project
return View::make('projects.edit')
->with('project', $project);
}

Categories