I have messaging system where users can write messages to administrator. The system works great except when Administrator open to read some message the name which should display from who is the message(username) shows the admin username instead.
On the front end user side all is correct.
I can't see where is the problem. Here is the admin message controller
public function messagesView($userId) {
/** #var User $user */
$user = User::where('user_id', $userId)->first();
if (!$user) {
App::abort(404);
}
$messages = $user->messages()->orderBy('created_at', 'asc')->get();
return View::make('site.admin.messages_view', [
'messages' => $messages
]);
}
public function messagesViewSubmit($userId) {
/** #var User $user */
$user = User::where('user_id', $userId)->first();
if (!$user) {
App::abort(404);
}
$validatorRules = array(
'message' => 'required|min:5',
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/admin/messages/view/' . $userId)->withErrors($validator->errors())->withInput(Input::all());
}
$message = new Message;
$message->user_id = $userId;
$message->text = Input::get('message');
$message->read_state = 0;
$message->from_admin = 1;
$message->save();
return Redirect::to('/admin/messages/view/' . $userId)->with('message_success', 'Message sent.');
}
Here is the view
#foreach($messages as $message)
#if($message->from_admin)
<div class="row">
<div class="media well col-xs-9">
<div class="media-left">
<img class="media-object" src="{{ URL::to('/img/admin.png') }}" alt="">
</div>
<div class="media-body user-message">
<h4 class="media-heading"><span style="font-weight: bold; color: red">Administrator {{{ $user['user_id'] }}}</span></h4>
<span>{{ $message->created_at }}</span>
<hr class="hr-sm-gray" />
{{ nl2br($message->text) }}
</div>
</div>
</div>
#else
<div class="row">
<div class="media well col-xs-9 col-xs-offset-3">
<div class="media-body text-right user-message">
<h4 class="media-heading">{{{ $user['username'] }}} - {{{ $user['user_id'] }}}</h4>
<span>{{ $message->created_at }}</span>
<hr class="hr-sm-gray" />
{{ nl2br(e($message->text)) }}
</div>
<div class="media-right">
<img class="media-object" src="{{ URL::to('/img/user.png') }}" alt="">
</div>
</div>
</div>
#if($message->read_state == 0)
{{ $message->markAsRead() }}
#endif
#endif
#endforeach
Messages model
protected $table = 'messages';
protected $primaryKey = 'message_id';
public function user() {
return $this->belongsTo('User', 'user_id', 'user_id');
}
public function markAsRead() {
$this->read_state = '1';
$this->save();
And this I have in User model
public function messages() {
return $this->hasMany('Message', 'user_id', 'user_id');
}
May be is session related.. here is what I have in BaseController where I check if user is logged in and if is admin or not.
protected function setupLayout()
{
if (!is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
$user = self::getCurrentUser();
View::share('isLoggedIn', self::isLoggedIn());
View::share('user', $user);
if (self::isLoggedIn()) {
View::share('messagesCount', $user->messages()->where('read_state', '0')->where('from_admin', '1')->count());
}
}
public static function isLoggedIn() {
$user = Session::get('user', null);
if ($user !== null) {
return true;
} else {
return false;
}
}
public static function isAdmin() {
if (!self::isLoggedIn()) {
return false;
}
$user = self::getCurrentUser();
return (bool)$user->is_admin;
}
public static function getCurrentUser() {
if (!self::isLoggedIn()) {
return null;
}
$user = Session::get('user', null);
if (self::$user == null) {
$user = User::where('user_id', $user['user_id'])->first();
self::$user = $user;
}
return self::$user;
}
It is because you select current user username in else block
<h4 class="media-heading">{{{ $user['username'] }}} - {{{ $user['user_id'] }}}</h4>
Try to replace it to
<h4 class="media-heading">{{{ $message->user->username }}} - {{{ $user['user_id'] }}}</h4>
This way you will select user from users table.
Related
In Laravel 7, I am have a task management app. I can upload tasks (posts if it were a blog) and images. I have a multiple image upload working as expected. When it comes time to delete a task, the task deletes just fine but the images are left in the database and in the disk which is public into a folder called task-images. Being new to Laravel, I am struggling on how to go about this. I tried to change the settings in the filesystem.php (which I will post with the commented out code) but that didn't change the location as I had expected. In the end, I want to be able to delete the multiple images when I delete a post and also click delete on an individual image and delete that from both db and disk. I am using resource controller for all my task routes. I have no idea how to go about this and the tutorials that I have found don't really address my specific issue. Any help would be greatly appreciated. Thank you in advance.
Here is my task controller at TaskController.php
<?php
namespace App\Http\Controllers;
use App\Task;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class TasksController extends Controller
{
public function index()
{
$tasks = Task::orderBy('created_at', 'desc')->paginate(10);
return view('/tasks')->with('tasks', $tasks);
}
public function create()
{
return view('tasks.create');
}
public function store(Request $request)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
// Create Task
$user = Auth::user();
$task = new Task();
$data = $request->all();
$task->user_id = $user->id;
$task = $user->task()->create($data);
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
$images = new Image;
$images->name = $name;
}
}
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->task_status;
$task->save();
return redirect('/home')->with('success', 'Task Created');
}
public function edit($id)
{
$task = Task::find($id);
return view('tasks.edit', ['task' => $task]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
$task->update();
return redirect('/home')->with('success', 'Task Updated');
}
public function show($id)
{
$task = Task::find($id);
return view('tasks.show')->with('task', $task);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
// $image = '/task-images/' . $task->image;
Storage::delete($task->image);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
filesystem.php (just the disks section)
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
...
in my individual show template, show.blade.php complete in case there is a code conflict.
#extends('layouts.master')
#section('content')
<div class="container">
Go Back
<div class="card p-3">
<div class="row">
<div class="col-md-4 col-sm-12">
<h3>Task</h3>
<p>{{ $task->task_name }}</p>
<h3>Assigned On:</h3>
<p>{{ $task->created_at->format('m/d/Y') }}</p>
<h3>Assigned To:</h3>
<p>{{ $task->task_assigned_to }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Task Description</h3>
<p>{{ $task->task_description }}</p>
<h3>Priority</h3>
<p>{{ $task->task_priority }}</p>
<h3>Status</h3>
<p>{{ $task->task_status }}</p>
</div>
<div class="col-md-4 col-sm-12">
<h3>Test Environment Date:</h3>
<p>{{ $task->task_to_be_completed_date }}</p>
<h3>Notes</h3>
<p>{{ $task->task_notes }}</p>
<h3>Action</h3>
<div style="display: inline;">
<a href="/tasks/{{$task->id}}/edit" class="btn btn-sm btn-primary mr-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
<form style="display: inline;" action="/tasks/{{ $task->id }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
<div class="col-md-12">
<h5>Images</h5>
<hr />
<div class="row">
#if($task->image->count()>0)
#for($i=0; $i < count($images = $task->image()->get()); $i++)
<div class="col-lg-4 col-md-6 col-sm-12">
<img class="w-50 mb-2" src="/task-images/{{ $images[$i]['name'] }}" alt="">
<form style="display: inline;" action="/tasks/{{ $task->name }}" method="POST" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</div>
#endfor
#else
<p>No images found</p>
#endif
</div>
<br />
</div>
</div>
</div>
</div>
<!--Modal Start-->
<div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-content">
<div class="modal-body">
<img class="w-100" src="" alt="" />
</div>
</div>
</div>
</div>
<!--Modal End-->
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var $lightbox = $('#lightbox');
$('[data-target="#lightbox"]').on('click', function(event) {
var $img = $(this).find('img'),
src = $img.attr('src'),
alt = $img.attr('alt'),
css = {
'maxWidth': $(window).width() - 100,
'maxHeight': $(window).height() - 100
};
$lightbox.find('.close').addClass('hidden');
$lightbox.find('img').attr('src', src);
$lightbox.find('img').attr('alt', alt);
$lightbox.find('img').css(css);
});
$lightbox.on('shown.bs.modal', function (e) {
var $img = $lightbox.find('img');
$lightbox.find('.modal-dialog').css({'width': $img.width()});
$lightbox.find('.close').removeClass('hidden');
});
});
</script>
#endsection
In my Task model, Task.php, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
class Task extends Model
{
protected $fillable = [
'task_name', 'task_priority', 'task_assigned_to', 'task_assigned_by', 'task_description', 'task_to_be_completed_date', 'task_status',
'task_notes'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function image()
{
// return $this->hasMany('App\Image');
return $this->hasMany(Image::class);
}
}
and finally my Image Model Image.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Task;
class Image extends Model
{
protected $fillable = [
'task_id',
'name',
];
protected $uploads = '/task-images/';
public function getFileAttribute($image)
{
return $this->uploads . $image;
}
public function task()
{
// return $this->belongsTo('App\Task', 'task_id');
return $this->belongsTo(Task::class);
}
}
If I am missing something, please let me know so I can edit my question. Again, thank you in advance for helping me with this issue. I have been scratching my head all week on this one. Cheers.
Edit
After implementing boot functions in my model as suggested below, I received an error that an invalid argument was used for foreach. I ran a dd($task); and the following image shows the result.
Final Edit
The answer below worked for my situation. I did have to edit some things to finalize the resolution:
in Task.php I changed the foreach to the following.
foreach($task->image ?: [] as $image)
I had declared image and not image in my model and that was causing a problem. Adding the ternary operator also helped the code not throw any errors.
In my TasksController.php I changed both the update and create functions with the same ternary operator as follows:
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach ($files ?: [] as $file) {
$name = time() . '-' . $file->getClientOriginalName();
$name = str_replace(' ', '-', $name);
$file->move('task-images', $name);
$task->image()->create(['name' => $name]);
}
}
I hope this helps anyone else having the same issue. Thanks to #GrumpyCrouton and #lagbox for their help in resolving this as well as #user3563950
Without them, I would still by stratching my head for another couple of weeks.
on your App\Image class, implement to boot function with the following;
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($image) {
Storage::delete(Storage::path($image->name));
});
}
Also implement the boot method in App\Task class
use Illuminate\Support\Facades\Storage;
public static function boot() {
parent::boot();
self::deleting(function($task) {
foreach($task->images as $image) {
$image->delete();
}
});
}
Now on your TaskController implement the destroy method as follows;
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
As a bonus, learn Laravel model binding to ease the pain of finding an instance using findOrFail()
I have this section on my website: [1]: https://imgur.com/a/xJjb1ww "section"
I want to limit this photos to show max. 4 contacts, because if I have more, it looks bad.How can I add to this a max. limit to show?Sorry for so much code but I don't know exactly where is my function.Thank you.
Here is my view:
<!-- Tabs Widget -->
<div class="tab-content" style="padding: 8px !important">
<?php $count_user = 0; ?>
#foreach($user->contact as $contact)
<div id="contact<?php echo $count_user++; ?>" class="tab-pane magazine-sb-categories <?php if($count_user == 1){ echo "active"; } ?>">
<div class="row team-v1">
<ul class="list-unstyled col-xs-12" style="margin-bottom: -10px">
<li><h3 style="margin-top: 5px !important;text-transform: none; " >
#if($contact->role[0]->slug == "individuals")
<i style="font-size: 13px;" class="icon-user"></i>
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px;" class="icon-hotel-restaurant-172 u-line-icon-pro fa- fa-lg"></i>
#endif
<a style="font-size: 14px" href="{{ url('') }}/{{ $contact->username }}">{{ $contact->username }}</a></h3>
<p>
<strong><i class="icon-real-estate-020 u-line-icon-pro"></i> : </strong><a>{{ $contact->country->country }}</a><br>
<strong><i class="icon-screen-tablet fa-" aria-hidden="true"></i> : </strong><a>{{ $contact->industry->industry }}</a><br>
#if($contact->role[0]->slug == "individuals")
#foreach($contact->career_path as $career_path)
<i style="font-size: 13px" class="icon-speedometer"></i> : {{ $career_path->functions->function }}
#break;
#endforeach
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px" class="icon-frame fa-"></i> : {{ $user->organization_type->organization_type }}<br>
#endif
</p>
</ul>
</div>
#endforeach
Here is my User.php:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class User extends Authenticatable
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
// protected $fillable = [
// 'name', 'email', 'password',
// ];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// protected $hidden = [
// 'password', 'remember_token',
// ];
public function comment()
{
return $this->hasMany('App\Comment');
}
public function country()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Country','country_id','id');
}
public function organization_type()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\OrganizationType');
}
public function industry()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Industry');
}
public function career_path()
{
return $this->hasMany('App\CareerPath');
}
public function education()
{
return $this->hasMany('App\Education');
}
public function about()
{
return $this->hasOne('App\About');
}
public function portfolio()
{
return $this->hasOne('App\Portfolio');
}
public function language_skills_selected()
{
return $this->belongsToMany('App\LanguageSkill','language_skills_selected','user_id','language_skills');
}
public function offices_branch()
{
return $this->hasMany('App\OfficesBranch');
}
public function my_alert()
{
return $this->hasOne('App\MyAlert');
}
public function privancy_setting()
{
return $this->hasOne('App\PrivancySetting');
}
public function event()
{
return $this->hasMany('App\Event');
}
public function news()
{
return $this->hasMany('App\News');
}
public function opinion()
{
return $this->hasMany('App\Opinion');
}
public function career_solution()
{
return $this->hasMany('App\CareerSolution');
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id');
}
public function user()
{
return $this->belongsToMany('App\User','contacts','user_id','contact_id');
}
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id')->limit(4);
}
This should be done in User.php.
If you have a relationship set up for $user->contact (i.e. hasMany), you should be able to call it like this in your loop in your blade file:
$limitedContacts = $user->contact->limit(4);
#foreach($limitedContacts as $contact)
....
#endforeach
After I send the variable that contains the comments to the view, I can only display the user id. This is why I need to somehow foreach through all the comments and based on their user_id to add a new key-pair value with username-username and send it to the view afterwards. Unfortunately, I'm having trouble figuring how to do that.
public function specificImage($id){
$similarImages = null;
$image = Image::with('comments.user')->find($id);
$subImages = Image::where('parent_id', $id)->get();
$views = $image->views;
$image->views = $views + 1;
$image->save();
$authorId = $image->user_id;
$author = User::find($authorId);
$comments = Comment::where('image_id', $id)->get();
$recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();
$tag = Tag::whereHas('images', function($q) use ($id) {
return $q->where('taggable_id', $id);
})->first();
if (!empty($tag)) {
$tagId = $tag->id;
}
if (!empty($tagId)) {
$similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
return $q->where('tag_id', $tagId);
})->orderBy('created_at', 'desc')->limit(9)->get();
}
return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}
Table:
Table: Comments
Columns: id, user_id, image_id, comment
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->morphToMany('App\Tag', 'taggable');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function updateVotes()
{
$this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
$this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
$this->save();
}
public function updateComments()
{
$this->comments = Comment::where('image_id', $this->id)->count();
$this->save();
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function image(){
return $this->belongsTo('App\Image');
}
public function user(){
return $this->belongsTo('App\User');
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function roles(){
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)){
return true;
}
}
} else {
if ($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if ($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
}
Blade
#extends('layouts.app')
#section('content')
<div class="specific-image-flexbox">
<div class="specific-image-column">
<div class='specific-image-container'>
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
#foreach($subImages as $subImage)
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
#endforeach
</div>
</div>
<div class="artwork-info-column">
<div class="artwork-info-container">
<p class='title'>{{ $image->name }}<p>
<p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
#endif
#endif
<p class='description'>{{ $image->description }}</p>
<p class='description'>Техника: {{ $image->medium }}</p>
<p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
<p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
<p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
<a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
<!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->
<div class='social-container'>
<div class="addthis_inline_share_toolbox"
data-url="{{ url()->full() }}"
data-title="{{ $image->name }} by {{ $author->username }}"
data-description="{{ $image->description }}"
data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
</div>
</div>
#if(!empty($recentImages))
#if(count($recentImages) >= 9)
<p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
<div class="more-images-container">
#foreach($recentImages as $recentImage)
<div class="more-images-container-element">
<a href='{{url("image/".$recentImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#if(!empty($similarImages))
#if(count($similarImages) >= 9)
<p class='similar-images'>Подобни произведения</p>
<div class="similar-images-container">
#foreach($similarImages as $similarImage)
<div class="similar-images-container-element">
<a href='{{url("image/".$similarImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#auth
<div class='postComments'>
<form method='POST' action=''>
<textarea class='comment-section' name='comment'></textarea>
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<input type="hidden" name="image_id" value="{{ $image->id }}">
<button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
</form>
</div>
#endauth
<div class='comments'>
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
</div>
</div>
</div>
</div>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment') }}';
var urlLike = '{{ route('vote') }}';
</script>
#endsection
I would suggest adding the user relationship to your Comment model as well:
class Comment extends Model
{
public function image()
{
return $this->belongsTo('App\Image');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
You can then eager load the relationships and then access them in your blade file:
public function specificImage($id)
{
$image = Image::with('comments.user')->find($id);
return view('specificImage', ['image' => $image]);
}
Then in your blade file you would have something like:
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
My route:
Route::get('/user/{username}', [
'uses' => '\MostWanted\Http\Controllers\ProfileController#getProfile',
'as' => 'profile.index',
]);`
My Controller:
use MostWanted\Models\User;
use Illuminate\Http\Request;
class ProfileController extends Controller{
public function getProfile($username){
$user = User::where('username', $username)->first();
if (!$user) {
abort(404);
}
return view('profile.index')
->with('user', $user);
}
}
The username field in the database exists and is filled in. When I go into search, the users pop up but the URL always misses out on the {username}. When I manually enter the {username} e.g. mostwanted.dev:8000/user/yes.man, it functions normally.
EDIT: This is the view that is hooked to (userblock.blade.php)
<div class="media">
<a class="pull-left" href="{{ route('profile.index', ['username' => $user->username]) }}">
<img class="media-object" alt="{{ $user->getNameOrUsername() }}" src="">
</a>
<div class="media-body">
<h4 class="media-heading">
{{ $user->getNameOrUsername() }}
</h4>
#if ($user->location)
<p>{{ $user->location }}</p>
#endif
</div>
Here is the User.php:
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'users';
protected $fillable = [
'username',
'first_name',
'last_name',
'email',
'password',
'location',
'gender',
'date_of_birth',
];
protected $hidden = [
'password',
'remember_token',
];
public function getName()
{
if ($this->first_name && $this->last_name) {
return "{$this->first_name} {$this->last_name}";
}
if ($this->first_name) {
return $this->first_name;
}
return null;
}
public function getUsername()
{
if ($this->first_name && $this->last_name) {
return "{$this->first_name}.{$this->last_name}";
}
if ($this->first_name) {
return $this->first_name;
}
return null;
}
public function getNameOrUsername()
{
return $this->getName() ?: $this->username;
}
public function getUsernameOrName()
{
return $this->getUsername() ?: $this->username;
}
public function getFirstNameOrUsername()
{
return $this->first_name ?: $this->username;
}
}
EDIT**: Search results view:
#extends('templates.default')
#section('content')
<h3>Your search for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No results found.</p>
#else
<div class="row">
<div class="col-lg-12" style="padding: 50px;">
#foreach ($users as $user)
#include('user/partials/userblock')
#endforeach
</div>
</div>
#endif
#stop
SearchController:
use DB;
use MostWanted\Models\User;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function getResults(Request $request)
{
$query = $request->input('query');
if (!$query) {
return redirect()->route('home');
}
$users = User::where(DB::raw("CONCAT(first_name, ' ', last_name)"),
'LIKE', "%{$query}%")
->orWhere('username', 'LIKE', "%{query}%")
->get();
return view('search.results')->with('users', $users);
}
}
EDIT***:
ProfileController:
use MostWanted\Models\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function getProfile($username)
{
$user = User::where('username', $username)->first();
if (!$user) {
abort(404);
}
return view('profile.index')
->with('user', $user);
}
}
Try to modify userblock.blade.php
<div class="media">
<a class="pull-left" href="{{ url('user/'.$user->username) }}">
<img class="media-object" alt="{{ $user->getNameOrUsername() }}" src="">
</a>
<div class="media-body">
<h4 class="media-heading">
{{ $user->getNameOrUsername() }}
</h4>
#if ($user->location)
<p>{{ $user->location }}</p>
#endif
</div>
I would like to provide the functionality to change his/her password on his/her own on my web application but I found the error addressed on the title so can anyone help me to solve this?
url:
http://nuatthai.loc/auth/password
routing:
Route::post('auth/password', ['as' => 'auth.postPassword', 'uses' => 'PasswordController#postPassword']);
Route::get('auth/password', ['as' => 'auth.prePassword', 'uses' => 'PasswordController#prePassword']);
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Mail;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
class PasswordController extends Controller
{
use ResourceController;
public function __construct()
{
$this->middleware('role:' . Role::ADMIN + Role::OWNER + Role::MANAGER + Role::ACCOUNTANT);
}
protected function validator(array $data)
{
return Validator::make($data, [
'password' => 'required|confirmed|min:8',
]);
}
private function updateData(Request $request)
{
$user = User::find($this::getMyId());
$user->password = $request->input('password');
$user->remember_token = str_random(60);
$user->save();
return $user;
}
public function prePassword()
{
return view('auth.change');
}
public function postPassword($request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
\Session::flash('flash_error', $validator->messages());
$this->throwValidationException(
$request, $validator
);
}
$this::updateData($request);
}
}
view:
{{-- resources/views/auth/change.blade.php --}}
#extends('common.layout')
#section('header') #parent #endsection
#section('navbar') #include('common.navbar') #endsection
#section('sidebar') #include('common.sidebar') #endsection
#section('content')
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('action' => ['PasswordController#postPassword'], 'class' => 'form-horizontal')) !!}
<div class="form-group">
<label class="col-md-4 control-label input-lg">Password</label>
<div class="col-md-6">
<input type="password" class="form-control input-lg" name="password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label input-lg">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control input-lg" name="password_confirmation">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary btn-lg" style="margin-right: 15px;">
Reset Password
</button>
</div>
</div>
</form>
</div><!-- .panel-body -->
</div><!-- .panel --> #endsection
{{-- resources/views/auth/change.blade.php --}}
middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Role;
use App\UserRole;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $mode)
{
if(!\Auth::check()) {
// session expired.
return redirect()->guest('auth/login');
}
else {
$admin = $mode & Role::ADMIN;
$owner = $mode & Role::OWNER;
$manager = $mode & Role::MANAGER;
$accountant = $mode & Role::ACCOUNTANT;
$type = \Auth::user()->role->type;
if(($admin) && ($type == Role::ADMIN)) {
return $next($request);
}
if(($owner) && ($type == Role::OWNER)) {
return $next($request);
}
if(($manager) && ($type == Role::MANAGER)) {
return $next($request);
}
if(($accountant) && ($type == Role::ACCOUNTANT)) {
return $next($request);
}
return response('Access Denied.', 403);
}
}
}
Role:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\ResourceController;
class Role extends Model
{
use ResourceController;
const TABLE = 'common_roles';
const ROLE_ID = 'role_id';
const ROLE_TYPE = 'type';
const TABLE_ROLE_ID = self::TABLE . '.' . self::ROLE_ID;
const TABLE_ROLE_TYPE = self::TABLE . '.' . self::ROLE_TYPE;
protected $table = self::TABLE;
protected $primaryKey = self::ROLE_ID;
const ADMIN = 0b1000; // 8
const OWNER = 0b100; // 4
const MANAGER = 0b10; // 2
const ACCOUNTANT = 0b1; // 1
public function users()
{
return $this->hasMany('App\User');
}
}
I really appreciate of any suggestions and advices in advance.