I'm trying to add a delete functionality into my project where the user can delete their status but I get the following error :
Screenshot of error
This is my HomeCotroller class:
namespace App\Http\Controllers;
use App\Eloquent\Status;
use App\Friends;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Laracasts\Flash\Flash;
//use Request;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if (Input::has('like_status')) {
$status = Input::get('like_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->create([
'user_id' => Auth::user()->id,
'status_id' => $status
]);
return redirect(route('home'));
}
if (Input::has('post_comment')) {
$status = Input::get('post_comment');
$commentBox = Input::get('comment-text');
$selectedStatus = Status::find($status);
$selectedStatus->comments()->create([
'comment_text' => $commentBox,
'user_id' => Auth::user()->id,
'status_id' => $status
]);
Flash::message('Your comment has been posted');
return redirect(route('home'));
}
if (Input::has('status-text')) {
$text = e(Input::get('status-text'));
$rules = [
'status-text' => 'required|string',
];
$vaildator = Validator::make($request->all(), $rules);
if (Input::hasFile('status_image_upload')) {
$file = Input::file('status_image_upload');
$mime = $file->getMimeType();
$image = $request->file('status_image_upload');
$imageName = str_random(8) . '_' . $image->getClientOriginalName();
//$imageFull = str_random(8).'_'.$image->getClientOriginalExtension();
$userStatus = new Status();
$userStatus->status_text = $text;
$userStatus->image_url = $imageName;
$userStatus->type = 1;
$userStatus->user_id = Auth::user()->id;
if ($mime == "video/x-flv" || $mime == "video/mp4" || $mime == "application/x-mpegURL" || $mime == "video/MP2T" || $mime == "video/3gpp" || $mime == "video/quicktime" || $mime == "video/x-msvideo" || $mime == "video/x-ms-wmv") {//process upload}
$vaildator = Validator::make($request->all(), $rules);
if (!$vaildator->fails()) {
$image->move('status_videos', $imageName);
$userStatus->type = 2;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
} else {
$rules['status_image_upload'] = 'image';
$vaildator = Validator::make($request->all(), $rules);
if (!$vaildator->fails()) {
$image->move('status_images', $imageName);
$userStatus->type = 1;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
}
} else {
}
if (!$vaildator->fails()) {
$userStatus = new Status();
$userStatus->status_text = $text;
$userStatus->user_id = Auth::user()->id;
$userStatus->save();
Flash::success('Your status has been posted');
return redirect(route('home'));
} else {
return back()->with('error', 'Validation failed:' . $vaildator->errors);
}
}
//Get top 15 post
$user_id = Auth::id();
$all_friends = Friends::where(['friend_id' => $user_id, 'status' => 1])
->orWhere(['user_id' => $user_id, 'status' => 1])
->get();
$friends = [];
foreach ($all_friends as $val) {
array_push($friends, $val->user_id, $val->friend_id);
}
$unique_friends = array_unique($friends);
if (!empty($unique_friends)) {
$top_15_posts = Status::whereIn('user_id', $unique_friends)
->orderBy('id', 'DESC')
->take(15)
->get();
} else {
$top_15_posts = Status::where('user_id', $user_id)
->orderBy('id', 'DESC')
->take(15)
->get();
}
//Get available friend request
$user_id = Auth::id();
$available_req_count = Friends::where(['friend_id' => $user_id, 'status' => 0])
->orderBy('id', 'desc')
->get()
->count();
return view('home', [
'top_15_posts' => $top_15_posts,
'available_req_count' => $available_req_count
]);
}
public function destroy($status_id)
{
$status =Status::where('id',$status_id)->first();
$status->delete();
return redirect()->route('home')->with(['message' => 'Successfully deleted!']);
}
}
This is user-status-layout.blade
<div class="panel panel-default">
<div class="panel-heading">{{$user->name}} - {{$status->created_at->diffForHumans()}} </div>
<div class="panel-body">
<div class="row">
<div class="col-md-1">
<img src="{{$user->getAvatar()}}" class="img-responsive">
</div>
<div class="col-md-11">
<p>{{$status->status_text}}</p>
#if($status->type == 1)
<img src="{{asset('status_images/'.$status->image_url)}}" class="img-responsive" style="width: 100%;">
#endif
</div>
<div class="col-md-12">
<hr>
<ul class="list-unstyled list-inline">
<li>
<button class="btn btn-xs btn-info" type="button" data-toggle="collapse" data-target="#view-comments-{{$status->id}}" aria-expanded="false" aria-controls="view-comments-{{$status->id}}">
<i class="fa fa-comments-o"></i>View & Comment</button>
</li>
<li>
#if(\App\Eloquent\StatusLikes::where(['status_id'=>$status->id,'user_id'=>Auth::user()->id])->first())
#else
{!! Form::open() !!}
{!! Form::hidden('like_status',$status->id)!!}
<button type="submit" class="btn btn-info btn-xs">
<i class="fa fa-thumbs-up"></i>Like status
</button>
{!! Form::close ()!!}
</li>
<button type="submit" class="btn btn-danger">
Delete
</button>
#endif
<li>
{{$comment_count}} comments
</li>
<li>
{{$like_count}} likes
</li>
</ul>
</div>
</div>
<div class="panel-footer clearfix">
{!! Form::open() !!}
{!! Form::hidden('post_comment',$status->id) !!}
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" name="comment-text" id="comment-text" placeholder="Post a comment...">
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="fa fa-send"></i>Add</button>
</span>
</div>
</div>
{!! Form::close() !!}
<div class="collapse" id="view-comments-{{$status->id}}">
#if($comments->first())
#foreach($comments as $comment)
<div class="row">
<div class="col-md-1">
<img src="{{\App\Eloquent\User::find($comment->user_id)->getAvatar()}}" class="img-responsive">
</div>
<div class="col-md-11">
<ul class="list-inline list-unstyled">
<li>
{{\App\Eloquent\User::find($comment->user_id)->name}}
</li>
<li>
posted {{$comment->created_at->diffForHumans()}}
</li>
</ul>
<p> {{$comment->comment_text}}</p>
</div>
</div>
<hr>
#endforeach
#else
<p>This status contains no comments.</p>
#endif
</div>
</div>
</div>
</div>
web.php:
<?php
//use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/test', function () {
return Auth::user()->test();
});
Auth::routes();
Route::any('/home', 'HomeController#index')->name('home');
Route::group(['as' => 'user.'], function () {
Route::get('/front', function () {
return view('front');
});
Route::get('/settings', ['as' => 'settings', 'uses' => 'ProfileController#viewSettings']);
Route::post('/settings', ['as' => 'settings', 'uses' => 'ProfileController#saveSettings']);
Route::any('/profile/{userId}', ['as' => 'profile', 'uses' => 'ProfileController#viewProfile']);
Route::get('/search/{query?}', ['as' => 'search', 'uses' => 'SearchController#search']);
Route::get('users', function () {
return User::find(1)->toJson();
});
Route::get('/chat', function () {
return view('chat');
});
Route::get('/calendar', function () {
return view('calendar');
});
Route::resource('events', 'EventsController', ['only' => ['index', 'store', 'update', 'destroy']]);
//Friends route
Route::post('/friends/request', ['as' => 'friends', 'uses' => 'FriendsController#sendRequest']);
Route::get('/friends/viewReq', ['as' => 'friends', 'uses' => 'FriendsController#viewFriendReq']);
Route::post('/friends/reqAction', ['as' => 'friends', 'uses' => 'FriendsController#requestAction']);
// Route::get('/status-delete/{status_id}',['uses' => 'HomeController#getDeleteStatus', 'as'=> 'user.status.delete',
// 'middleware' =>'auth'
// ]);
});
Also this what I get from php artisan route:list
Screenshot of routes
If you look at the name column in the route list, you'll see it is named user.status.delete not status.delete. This must mean your route group must have 'as' => 'user.' set which is going to prefix all routes in that group with user..
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 wanna update the data of categories on multilevel choose item, but i had a problem, i can edit the categories without choose a parent, but i can't edit the categories when i choose a parent. then its showing a error called undefined offset:1 and here the trace error
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\laragon\www\oesingcoffee\vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php:874
this is validates attrib in laravel framework
protected function getExtraConditions(array $segments)
{
$extra = [];
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
$extra[$segments[$i]] = $segments[$i + 1]; //this is the 874 line
}
return $extra;
}
this is the CategoryRequest class
class CategoryRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$parentId = (int) $this->get('parent_id');
$id = (int) $this->get('id');
if($this->method() == 'PUT'){
if($parentId > 0){
$name = 'required|unique:categories,name,'.$id.'id,parent_id,'.$parentId;
}else{
$name = 'required|unique:categories,name,'.$id;
}
$slug = 'unique:categories,slug,'.$id;
}else{
$name = 'required|unique:categories,name,NULL,id,parent_id,'.$parentId;
$slug = 'unique:categories,slug';
}
return [
'name' => $name,
'slug' => $slug,
];
}
}
this is my controller to update the data
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->update($params)) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
this the view form
#extends('admin.layout')
#section('content')
#php
$formTitle = !empty($category) ? 'Update' : 'New'
#endphp
<div class="content">
<div class="row">
<div class="col-lg-6">
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>{{ $formTitle }} Category</h2>
</div>
<div class="card-body">
#include('admin.partials.flash', ['$errors' => $errors])
#if (!empty($category))
{!! Form::model($category, ['url' => ['admin/categories', $category->id], 'method' => 'PUT']) !!}
{!! Form::hidden('id') !!}
#else
{!! Form::open(['url' => 'admin/categories']) !!}
#endif
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'category name']) !!}
</div>
<div class="form-group">
{!! Form::label('parent_id', 'Parent') !!}
{!! General::selectMultiLevel('parent_id', $categories, ['class' => 'form-control', 'selected' => !empty(old('parent_id')) ? old('parent_id') : !empty($category['parent_id']) ? $category['parent_id'] : '', 'placeholder' => '-- Choose Category --']) !!}
</div>
<div class="form-footer pt-5 border-top">
<button type="submit" class="btn btn-primary btn-default">Save</button>
Back
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endSection
this is the migration
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->bigInteger('parent_id');
$table->timestamps();
});
}
this is the edit method in controller
public function edit($id)
{
$category = Category::findOrFail($id);
$categories = Category::orderBy('name', 'asc')->get();
$this->data['categories'] = $categories->toArray();
$this->data['category'] = $category;
return view('admin.categories.form', $this->data);
}
you should try save() method.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->save()) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
Replace with above one.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$category = Category::findOrFail($id);
$category->slug = Str::slug($params['name']);
$category->parent_id = (int)$params['parent_id'];
$category->save();
Session::flash('success', 'Category has been updated.');
return redirect('admin/categories');
}
I think your issue is inyour validation rule (specifically in your unique rule). May I suggest something else ?
I don't have the environment to test it right but now, so it may have some tweak to do.
use Illuminate\Validation\Rule;
...
public function rules()
{
$name = [
'required',
Rule::unique('categories')->where(function ($query) {
return $query->where('name', $this->name)
->where('parent_id', $this->parent_id);
})->ignore($this->id, 'id'),
];
$slug = [
Rule::unique('categories', 'slug')->ignore($this->id, 'id'),
];
return [
'name' => $name,
'slug' => $slug,
];
}
Question
Why my variable in ProfileController is not loaded in my blade(index2.blade.php)?
Error Message
Undefined variable: plus (View: /work/resources/views/stories/index2.blade.php)
My Codes
routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Route::get('login');
Route::match(['get','post','middleweare'=>'auth'], '/',
'StoriesController#index',
'StoriesController#store',
'ProfileController#index',
'ProfileController#store'
);
Route::match(['get','post','middleweare'=>'auth'], 'stories/create',
'StoriesController#add',
'StoriesController#upload'
);
Route::match(['get','post','middleweare'=>'auth'], 'profile/create',
'ProfileController#add',
'ProfileController#upload'
);
Route::group(['middleweare' => 'auth','name'=>'profile'], function () {
Route::get('/profile/edit', 'ProfileController#edit');
});
Route::get('/home', 'HomeController#index')->name('home');
Auth::routes();
app/Http/Controllers/ProfileController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\stories;
use App\History;
use App\Posts;
use Carbon\Carbon;
use Storage;
class ProfileController extends Controller
{
public function index(Request $request)
{
$plus = Posts::all();
return view('stories.index2', compact('plus'));
}
public function upload(Request $request)
{
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
return view('stories.index2')->with('filename', basename($path));
} else {
return redirect()
->back()
->withInput()
->withErrors();
}
}
public function store(Request $request)
{
$d = new \DateTime();
$d->setTimeZone(new \DateTimeZone('Asia/Tokyo'));
$dir = $d->format('Y/m');
$path = sprintf('public/posts/%s', $dir);
$data = $request->except('_token');
foreach ($data['plus'] as $k => $v) {
$filename = '';
$posts = Posts::take(1)->orderBy('id', 'desc')->get();
foreach ($posts as $post) {
$filename = $post->id + 1 . '_' . $v->getClientOriginalName();
}
unset($post);
if ($filename == false) {
$filename = 1 . '_' . $v->getClientOriginalName();
}
$v->storeAs($path, $filename);
$post_data = [
'path' => sprintf('posts/%s/', $dir),
'name' => $filename
];
$a = new Posts();
$a->fill($post_data)->save();
}
unset($k, $v);
return redirect('/');
}
public function create(Request $request)
{
$this->validate($request, Profile::$rules);
$profile = new Profile;
$form = $request->all();
unset($form['_token']);
$profile->fill($form);
$profile->save();
return redirect('/');
}
public function add()
{
return view('profile.create2');
}
public function edit()
{
return view('profile.edit');
}
}
resources/views/stories/index2.blade.php
#extends('layouts.front2')
#section('title','mainpage')
#section('content')
<div class="profile">
<div class="profileimg">
#foreach ($plus as $pplus)
<img src="/storage/{{ $pplus->path . $pplus->name }}" style="height: 210px; width: 210px; border-radius: 50%;">
#endforeach
</div>
<div class="name">
#guest
<a class="nav-link2" href="{{ route('register')}}">{{ __('Create Accout!')}}</a>
#else
<a id="navbarDropdown" class="nav-link2" href="#" role="button">
{{Auth::user()->name}}<span class="caret"></span></a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
#csrf
</form>
</div>
#endguest
<div class="aboutme">
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
You can write your profile here!You can write your profile here!You can write your profile here!
</div>
</div>
<div class="new">
<div class="newtitle">
<h1>New</h1>
</div>
<div class="container1">
#foreach ($plus as $pplus)
<img src="/storage/{{ $pplus->path . $pplus->name }}" class="images" style="height: 150px; width: 150px; border-radius: 50%;">
#endforeach
<div class="more">
more...
</div>
</div>
</div>
<div class="stories">
<div class="titlestories">
<h1>Stories</h1>
</div>
<div class="container2">
<div class="titleclose">
<h2>#CloseFriends</h2>
</div>
<div class="titlefollow">
<h2>#Follows</h2>
</div>
</div>
</div>
{{ csrf_field() }}
#endsection
In your upload method, you're missing the $plus variable
Change it to this
public function upload(Request $request)
{
$this->validate($request, [
'file' => [
'required',
'file',
'image',
'mimes:jpeg,png',
]
]);
if ($request->file('file')->isValid([])) {
$path = $request->file->store('public');
$filename = basename($path);
$plus = Posts::all();
return view('stories.index2', compact('filename','plus'));
} else {
return redirect()
->back()
->withInput()
->withErrors();
}
}
return view('stories.index2, [ 'plus' => Posts::all() ]); should work.
I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag
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.