I'm writing applications from tutorial for booking tourist objects in laravel 8. I have a problem redirecting to the website after adding a comment and liking the object. When I click "like" or "add comment" it shows me an error below. Any ideas what im doing wrong?
Error:
Not Found
The requested URL was not found on this server.
Apache/2.4.52 (Win64) OpenSSL/1.1.1m PHP/7.4.27 Server at localhost Port 80
My files for likes
Object.blade.php:
#auth
#if( $touristObject->isLiked() )
Odlub ten obiekt
#else
Polub ten obiekt
#endif
#else
<p>Zaloguj się aby polubić obiekt</p>
#endauth
FrontendController:
public function like($likeable_id, $type, Request $request)
{
$this->fR->like($likeable_id, $type, $request);
return redirect()->back();
}
public function unlike($likeable_id, $type, Request $request)
{
$this->fR->unlike($likeable_id, $type, $request);
return redirect()->back();
}
FrontendRepository:
public function like($likeable_id, $type, $request)
{
$likeable = $type::find($likeable_id);
return $likeable->users()->attach($request->user()->id);
}
public function unlike($likeable_id, $type, $request)
{
$likeable = $type::find($likeable_id);
return $likeable->users()->detach($request->user()->id);
}
Model TouristObject:
public function isLiked()
{
return $this->users()->where('user_id',Auth::user()->id)->exists();
}
My files for comments
object.blade.php:
#auth
<a class="btn btn-primary" role="button" data-toggle="collapse" href="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Dodaj komentarz
</a>
#else
<p>Zaloguj się aby dodać komentarz</p>
#endauth
<div class="collapse" id="collapseExample">
<div class="well">
<form method="POST" action="{{ route('addComment',['commentable_id'=>$touristObject->id, 'App\TouristObject']) }}" class="form-horizontal">
<fieldset>
<div class="form-group">
<label for="textArea" class="col-lg-2 control-label">Skomentuj</label>
<div class="col-lg-10">
<textarea required name="content" class="form-control" rows="3" id="textArea"></textarea>
<span class="help-block">Dodaj komentarz do tego obiektu</span>
</div>
</div>
FrontendRepository:
public function addComment($commentable_id, $type, $request)
{
$commentable = $type::find($commentable_id);
$comment = new Comment;
$comment->content = $request->input('content');
$comment->rating = $type == 'App\TouristObject' ? $request->input('content') : 0;
$comment->user_id = $request->user()->id;
return $commentable->comments()->save($comment);
}
FrontendGateway:
public function addComment($commentable_id, $type, $request)
{
$this->validate($request, [
'content' => "required|string"
]);
return $this->fR->addComment($commentable_id, $type, $request);
}
Routes:
Route::get('/like/{likeable_id}/{type}','FrontendController#like')->name('like');
Route::get('/unlike/{likeable_id}/{type}','FrontendController#unlike')->name('unlike');
Route::post('/addComment/{commentable_id}/{type}','FrontendController#addComment')->name('addComment');
Related
hello guys I'm new to laravel and livewire please kindly assist, post request not going through , if i click on the submit nothing is happening, I'm not getting error either, I have added the livewire script in my app.blade.php and it's rendering properly
Post Create form
<div>
<div class="p-4 mx-auto mt-3 bg-gray-100 md:p-8 md:w-4/5 md:mt-0">
<h1 class="mb-3 text-xl font-semibold text-gray-600">New post</h1>
<form wire:submit.prevent="createPost" action="#" class="px-4 py-6 space-y-4">
<div class="overflow-hidden bg-white rounded-md shadow">
<div class="px-4 py-3 space-y-8 sm:p-6">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6 sm:col-span-3">
<input class="w-full" type="text"
wire:model="post.title" placeholder="Post title" />
</div>
</div>
<div class="flex flex-col">
<textarea id="body" rows="4" wire:model="post.body"
class="border-gray-300 rounded-sm form-textarea">
</textarea>
</div>
</div>
<div class="px-4 py-3 text-right bg-gray-50 sm:px-6">
<button type="submit" class="inline-flex justify-center">
post
</button>
</div>
</div>
</form>
</div>
</div>
this is my post create livewire method
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
use Illuminate\Http\Response;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'title' => 'required|min:4',
'body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = Post::create([
'user_id' => auth()->user()->id,
// 'category_id' => $this->category,
'body' => $this->body,
'title' => $this->title,
]);
$users = auth()->user();
$users->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
There are two thing here to note - you don't initialize $this->post and you don't have the proper validation. You need to check for post.title and post.body, and you also need to display the actual errors.
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
class PostCreate extends Component
{
public $post;
public $points = 10;
public $energy = 1;
public function mount()
{
$this->post = new Post;
$this->post->user_id = auth()->id();
}
public function increment()
{
$this->points++;
}
protected $rules = [
// 'category' => 'required|integer|exists:categories,id',
'post.title' => 'required|min:4',
'post.body' => 'required|min:4',
];
public function createPost()
{
if (auth()->check()) {
$this->validate();
$post = $this->post->save();
auth()
->user()
->increment('points', 10);
session()->flash('success_message', 'Post was added successfully!');
$this->reset();
return redirect()->route('posts.index');
}
// abort(Response::HTTP_FORBIDDEN);
}
public function render()
{
return view('livewire.post-create');
}
}
To display the errors from validation, you can add the following snippet in your blade-file,
#if ($errors->any())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
Add lazy to the wire.model:
<input class="w-full" type="text" wire:model.lazy="post.title" placeholder="Post title" />
<textarea id="body" rows="4" wire:model.lazy="post.body" class="border-gray-300 rounded-sm form-textarea"></textarea>
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 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');
});
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}}
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'));
}