Missing required parameters for [Route: voluntier.submit.get] [URI: voluntier/submit/{id}] - php

I am currently working on my final project, but I got this error and I have tried to change the route action on my html to {{ route('voluntier.submit.get') }} but it still shows the error. Could anyone help me to find the solution.
Thank you so much
VoluntierController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Event;
use App\City;
use App\User;
use App\VoluntierProfile;
use App\Submission;
class VoluntierController extends Controller
{
public function index()
{
$data = Event::select('events.job_desk', 'events.location', 'events.city', 'events.job_description', 'events.fee', 'cities.name as city', 'job_desks.job_desk')
->leftJoin('job_desks', 'events.job_desk', 'job_desks.id')
->leftJoin('cities', 'events.city', 'cities.id')
->get();
$data_category_liaison = Event::select('events.job_desk')
->where('id' , '=', 2)
->count();
// dd($data_category);
return view('voluntier.index', compact('data', 'data_category_liaison'));
}
public function profile()
{
return view('voluntier.profile');
}
public function createProfile()
{
$city = City::all()->where('id', '!=', '0');
return view('voluntier.profile-edit', compact('city'));
}
public function storeProfile(Request $request)
{
$profile = new VoluntierProfile();
$profile->voluntier_id = $request->input('voluntier_id');
$profile->about = $request->input('tentang');
$profile->city_id = $request->input('kota');
$profile->address = $request->input('alamat');
$profile->latest_education = $request->input('pendidikan_terakhir');
$profile->save();
}
public function submitCreate($id)
{
$event = Event::find($id)->first();
$voluntier = Voluntier::find(Auth::user()->id)->get();
// dd($voluntier);
return view('voluntier.submit', compact('data'));
}
public function submitStore($id, Request $request)
{
$event = Event::find($id);
$voluntier = Auth::user();
$submission = new Submission();
$submission->event_id = $event->id;
$submission->voluntier_id = $voluntier->id;
$submission->status_id = $request->input('status');
$submission->save();
return redirect('voluntier/dashboard');
}
}
index.blade.php
#foreach($data as $row)
<td><a href="{{ route('voluntier.submit.get', $row->id) }}" class="job-item d-block d-md-flex align-items-center border-bottom fulltime">
<div class="company-logo blank-logo text-center text-md-left pl-3">
<img src="images/company_logo_blank.png" alt="Image" class="img-fluid mx-auto">
</div>
<div class="job-details h-100">
<div class="p-3 align-self-center">
<h3>{{ $row->job_desk }}</h3>
<div class="d-block d-lg-flex">
<div class="mr-3"><span class="icon-suitcase mr-1"></span>{{ $row->location }}</div>
<div class="mr-3"><span class="icon-room mr-1"></span>{{ $row->city }}</div>
<div><span class="icon-money mr-1"></span>Rp. {{ $row->fee }}</div>
</div>
</div>
</div>
<!-- <div class="job-category align-self-center">
<div class="p-3">
<span class="text-info p-2 rounded border border-info">Full Time</span>
</div>
</div> -->
</a></td>
#endforeach
submit.blade.php
<form action="{{ route('voluntier.submit.post', $event->id) }}" method="post" class="p-5 bg-white">
My route
web.php
Route::prefix('voluntier')->group(function() {
Route::get('/login', 'Auth\LoginController#showVoluntierLoginForm')->name('voluntier.login.get');
Route::post('/login/post', 'Auth\LoginController#voluntierLogin')->name('voluntier.login.post');
Route::get('/register', 'Auth\RegisterController#showVoluntierRegisterForm')->name('voluntier.register.get');
Route::post('/register/post', 'Auth\RegisterController#createVoluntier')->name('voluntier.register.post');
Route::get('/dashboard', 'VoluntierController#index')->middleware('auth:voluntier')->name('voluntier.dashboard');
Route::get('/profile', 'VoluntierController#profile')->middleware('auth:voluntier')->name('voluntier.get');
Route::get('/profile/get', 'VoluntierController#createProfile')->middleware('auth:voluntier')->name('voluntier.profile.get');
Route::post('/profile/post', 'VoluntierController#storeProfile')->name('voluntier.profile.post');
Route::get('/submit/{id}', 'VoluntierController#submitCreate')->middleware('auth:voluntier')->name('voluntier.submit.get');
Route::post('submit/post/{id}', 'VoluntierController#submitStore')->name('voluntier.submit.post');
});

Related

Laravel 7 Invalid argument supplied for foreach() when trying to delete post with multiple images

I am running Laravel 7 and have a list of tasks (would be posts if it were a blog) and I need to make sure that when the task is deleted, that all subsequent images are deleted in both the database and in the disc. When I click the delete button, the page throws an error: Invalid argument supplied for foreach().
Unfortunately, this is a vague error and can be caused by a variety of causes. My hopes are that someone can take a look at my code and see if I am missing something. I am relatively new to Laravel so tracking down this issue has been more than a challenge. Than you in advance for helping my work out this issue.
In my Task.php model, I have:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Image;
use Illuminate\Support\Facades\Storage;
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);
}
public static function boot()
{
parent::boot();
self::deleting(function ($task) {
foreach ($task->images as $image) {
$image->delete();
}
});
}
}
In my Image.php model, I have
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
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);
}
public static function boot()
{
parent::boot();
self::deleting(function ($image) {
Storage::delete(Storage::path($image->name));
});
}
}
In my TasksController.php, (all code in case something is causing a conflict here) here is what I have:
<?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);
// dd($task);
$task->delete();
return redirect('home')->with('success', 'Task Deleted');
}
}
And in the home page where I am calling the delete function, `home.blade.php`, I have:
#extends('layouts.master')
#section('content')
<div class="custom-container">
<div class="row justify-content-center">
<div class="col-md-12">
#include('layouts.includes.messages')
<div class="card w-100">
<div class="card-header text-white" style="background-color: #605ca8;">
<h3 class="card-title">Tasks</h3>
<div class="card-tools">
<a href="tasks/create" class="btn btn-success">
<i class="fas fa-tasks"></i> Add New Task
</a>
</div>
</div>
<!-- /.card-header -->
</div>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Ongoing Tasks</h3>
<div class="card-tools">
<div class="input-group input-group-sm" style="width: 150px;">
<input type="text" name="table_search" class="form-control float-right" placeholder="Search">
<div class="input-group-append">
<button type="submit" class="btn btn-default"><i class="fas fa-search"></i></button>
</div>
</div>
</div>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive p-0">
<table class="table table-hover text-nowrap">
<thead>
<tr>
<th>Task</th>
<th>Priority</th>
<th>Assigned To</th>
<th>Test Environment Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($tasks->count() > 0)
#foreach($tasks as $task)
<tr>
<td>{{ $task->task_name }}</td>
<td>{{ $task->task_priority }}</td>
<td>{{ $task->task_assigned_to }}</td>
<td>{{$task->task_to_be_completed_date }}</td>
<td>{{ $task->task_status }}</td>
<td>
<a href="tasks/{{$task->id}}/edit" class="btn btn-primary btn-sm mr-2">
<i class="fa fa-edit"></i> Edit
</a>
<form action="tasks/{{$task->id}}" method="POST" style="display: inline" class="">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger ml-1 mr-1">
<i class="fa fa-trash"></i> Delete
</button>
</form>
</td>
</tr>
#endforeach
#else
<p class="ml-4 pt-2">No Tasks Found. Please Add one.</p>
#endif
</tbody>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
</div>
{{ $tasks->links() }}
</div>
</div>
#endsection
In my filesystem.php under the config folder, I have(just for storage):
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
// 'root' => public_path('task-images'),
],
If I missed anything or codes, please let me know so I can edit my question. Thank you again in advance for helping me with this issue.
You are trying to access a property named images on your instance of Task but there isn't an attribute named images and there isn't a relationship named images, so null is being returned: $task->images == null. You named your relationship image not images, though images would be more correct since this relationship can return many; plural. Change the name of the relationship to images:
public function images()
{
return $this->hasMany(Image::class);
}
Or reference it by its current name: $task->image

Laravel 7 Delete array or single image from db and disk - Deletes post but not associated images from db nor disk

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 want to display username of comment's owner, however, comments table has user_id only

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

How I use relationship in blade template (hasOne) || Laravel

Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}

Laravel Searchform and Delete not working

So I have a search form for offices and delete for offices, also edit it those 2 were working before. But after I changed and fix edit form and button those are not working anymore the search is not working it shows this error
Undefined variable: building (View: C:\xampp\htdocs\Eguide\resources\views\search.blade.php)
The delete also show this error but it works after I go back to the office page it deleted it but it shows an error message:
Trying to get property 'name' of non-object (View: C:\xampp\htdocs\Eguide\resources\views\building.blade.php)
DD offices result
This is the controller for search and delete
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','like','%'.$search.'%')->get();
return view('search',compact('offices','search'));
}
public function store(Request $request, $id)
{
$office = new Office();
$office->name =$request->officename;
$office->floor = $request->floor;
$office->building_id = $id;
$office->save();
\Session::flash('building_flash', 'Created successfully!');
return redirect()->route('building', $id);
}
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
public function edit($id, $office_id) {
$office = Office::find($office_id);
return view('editoffice', compact('office', 'id'));
}
public function update(Request $request, $id, $office_id)
{
// echo $id.'--'.$office_id;exit;
//$office = Office::find($id);
$office = Office::find($office_id);
$office->name = $request->officename;
$office->floor = $request->floor;
$office->update();
\Session::flash('building_flash', 'Updated successfully!');
return redirect()->route('building', $id);
}
public function destroy($id)
{
$office = Office::find($id);
$office->delete();
\Session::flash('building_flash_delete', 'Deleted successfully!');
return redirect()->route('building', $id);
}
}
search.blade.php
No error in search when I remove this
Edit
<div class="search">
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search
</button>
</span>
</div>
{!! Form::close()!!}
</div>
<hr>
<table class="table">
<thead>
<th>Office Name</th>
<th>Belongs to</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->building->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
#endforeach
#endsection
I also have Building.php in app folder it has code like this
class Building extends Model
{
public $table = 'buildings';
public function offices(){
return $this->hasMany('App\Office');
}
}
Office.php
class Office extends Model
{
public function building(){
return $this->belongsTo('App\Building');
}
}
ROUTES
Route::get('/', 'BuildingController#index')->name('index');
Route::get('building/{id}', 'PageController#show')->name('building');
Route::get('office/{id}', 'OfficeController#show')->name('officeMenu');
Route::get('offices', 'OfficeController#index');
Route::group(['middleware' => ['auth']], function () {
Route::get('buildings/create', 'BuildingController#create')->name('createbform');
Route::post('building/create/store', 'BuildingController#saveBuilding')->name('createbuilding');
Route::get('building/{id}/edit', 'BuildingController#edit');
Route::post('building/{id}/edit', 'BuildingController#update')->name('editbuilding');
Route::get('building/{id}/delete', 'BuildingController#destroy');
Route::get('building/{id}/offices/create', 'OfficeController#create')->name('createofficeform');
Route::post('building/{id}/offices/create/store', 'OfficeController#store')->name('createoffice');
Route::get('building/{id}/offices/{office_id}/edit', 'OfficeController#edit')->name('editofficeform');
Route::post('building/{id}/offices/{office_id}/edit', 'OfficeController#update')->name('editoffice');
Route::get('offices/{id}/delete', 'OfficeController#destroy')->name('deleteoffice');
});
buildidng.blade.php
<div class="officebg">
<link href="https://fonts.googleapis.com/css?family=Anton" rel="stylesheet">
<div class="Bldgttl">
<div class="container">
<div class="row">
<div class="col-lg-12">
<img src="{{URL::to('/assets')}}/{{$building->picture}}" alt="" style="height:300px; width:500px;">
</div>
</div>
<div class="row">
<div class="col-lg-12">
{{$building->name}}
</div>
</div>
</div>
</div>
<div class="rows">
<div class="col-md-6 col-md-offset-3">
<div class="col-xs-4 col-md-6">
#if(!Auth::guest())
Create an Office
#endif
</div>
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md">Search</i>
</button>
</span>
</div>
{!! Form::close()!!}
<table class="table">
<div class="ttitle">
<thead>
<th>Office Name</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{optional($office)->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#endsection
You don't have a building defined in show.
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
What you can do is to load a building in show method
public function show($id)
{
$office = Office::find($id);
$building = Building::first();//some logic to find building
return view('office',['building' => $building, 'office' => $office]);
}
Your building.blade.php is trying to access the $building variable. Your show method in your controller is only passing $office as data. Since $building doesn't exist trying to get the name property of it is returning an error.
You need to either pass $building from the controller to the view, or if it is part of $office extrapolate $building from that variable.
public function show($id)
{
$office = Office::find($id);
$building = Buildng::where('id', '=', $office->building_id)->firstOrFail();
return view('office',compact('office', 'building'));
}

Categories