So I'm trying to use the update() function to update the selected user but when I click submit, it just goes back to index (as it should) but updates nothing. Following is my code:
StudentController (Resource Controller):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::all();
return view ('main',compact('students'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Student::create($request->all());
return redirect()->route('main.index')->with('create','Student has been added successfully!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id, Student $student)
{
$student = Student::findOrFail($id);
return view ('edit',compact('student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Student $student)
{
$student->update($request->all());
return redirect()->route('main.index')->with('update','Student has been updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Main.blade.php (Index):
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="py-4">
#if (Session::has('create'))
<div class="alert alert-info">
{{ Session::get('create') }}
</div>
#endif
#if (Session::has('update'))
<div class="alert alert-info">
{{ Session::get('update') }}
</div>
#endif
<div class="card">
<div class="card-header">
Students
{{ link_to_route('main.create','Add Student','',['class'=>'btn btn-success float-right']) }}
</div>
<div class="card-body">
<table id="myTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Student Name</th>
<th>Gender</th>
<th>Address</th>
<th>Class</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($students as $student)
<tr>
<td>{{ $student->name }}</td>
<td>{{ $student->gender }}</td>
<td>{{ $student->address }}</td>
<td>{{ $student->class }}</td>
<td>{{ link_to_route('main.edit','Edit',[$student->id],['class'=> 'btn btn-primary btn-sm']) }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
edit.blade.php (Model):
{!! Form::model($student,array('route'=>['main.update',$student->id],'method'=>'PUT')) !!}
<div class="form-group">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Add Student Name']) !!}
</div>
<div class="form-group">
{!! Form::select('gender', [
'Male' => 'Male',
'Female' => 'Female'],
null, ['class'=>'custom-select','placeholder' => 'Choose Gender']); !!}
</div>
<div class="form-group">
{!! Form::text('address',null,['class'=>'form-control','placeholder'=>'Add Student Address']) !!}
</div>
<div class="form-group">
{!! Form::select('class', [
'A' => 'A',
'B' => 'B',
'C' => 'C',
'D' => 'D',],
null, ['class'=>'custom-select','placeholder' => 'Choose Class']); !!}
</div>
<div class="form-group py-4">
{!! Form::submit('Edit',['type'=>'submit','class'=>'btn btn-danger btn-block']) !!}
</div>
{!! Form::close() !!}
Student.php (Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['name','gender','address','class'];
}
My create.blade.php is exactly the same as my edit.blade.php, the only changes are in the Form::open() line. And the edit page even displays my old data on the input fields but when I make a change & click Update, it just doesn't update anything in the database or the index page - so what am I doing wrong? Thanks in advance and please feel free to ask if any more code is required for you guys to crack this one.
Try this one out:
public function update(Request $request, Student $student)
{
$input = $request->all();
$student->fill($input)->save();
return redirect()->route('main.index')->with('update','Student has been updated!');
}
Try..
public function update(Request $request,$id)
{
$student = Student::find($id);
$student->name = $request->input('name');
$student->gender = $request->input('gender');
$student->address = $request->input('address');
$student->class = $request->input('class');
$student->save();
return redirect()->route('main.index')->with('update','Student has been updated!');
}
request()->all() contains method and token information. Can you maybe pass it through a validator?
$validated = request()->validate([
'name' => 'required',
'address' => '',
..
]);
$student->update($validated);
In your edit.blade.php,
{!! Form::submit('route_to_update()',['type'=>'submit','class'=>'btn btn-danger btn-block']) !!}
change "Edit"
And you can check your route by in your console like "php artisan route:list"
and check your route is reached
by var_damp() or var_export() or dd()in your student controller update function
Related
i found out that these 2 lines cause the problem, but i don't know how to rewrite them to proceed
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
Here is my posts/index.blade.php
#extends('layouts.app')
#section('content')
<div class="d-flex justify-content-end mb-2">
Add Post
</div>
<div class="card card-default">
<div class="card-header">Posts</div>
<div class="card-body">
#if ($posts->count()>0)
<table class="table">
<thead>
<th>Image</th>
<th>Title</th>
<th>Category</th>
<th></th>
<th></th>
<tbody>
#foreach($posts as $post)
<tr>
<td>
<img src="{{ asset('storage/'.$post->image) }}" width="120px" height="60px" alt="">
</td>
<td>
{{ $post->title }}
</td>
<td>
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
</td>
#if($post->trashed())
<td>
<form action="{{ route('restore-posts', ['post' => $post['id']]) }}" method="POST">
#csrf
#method('PUT')
<button type="submit" class="btn btn-info btn-sm">Restore</button>
</form>
</td>
#else
<td>
Edit
</td>
#endif
<td>
<form action="{{ route('posts.destroy', ['post' => $post['id']]) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger btn-sm">
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</thead>
</table>
#else
<h3 class="text-center">
No Posts Yet
</h3>
#endif
</div>
</div>
#endsection
and here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostRequest;
use App\Post;
use App\Category;
// use Illuminate\Support\Facades\Storage;
use App\Http\Requests\Posts\UpdatePostRequest;
class PostsController extends Controller
{
public function __construct(){
$this->middleware('verifyCategoriesCount')->only(['create','store']);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('posts.index')->with('posts', Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create')->with('categories', Category::all());
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$image = $request->image->store('posts');
Post::create([
'title' => $request->title,
'description' => $request->description,
'content' => $request->content,
'image' => $image,
'published_at' => $request->published_at,
'category_id' => $request->category
]);
session()->flash('success', 'Post created succesfully.');
return redirect(route('posts.index'));
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.create')->with('post', $post)->with('categories', Category::all());
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(UpdatePostRequest $request, Post $post)
{
$data = $request->only(['title', 'description', 'published_at', 'content']);
// check if new image
if($request->hasFile('image')){
// upload it
$image = $request->image->store('posts');
// delete old one
$post->deleteImage();
$data['image'] = $image;
}
// update attributes
$post->update($data);
// falsh message
session()->flash('success', 'Post updated succesfully');
// redirect user
return redirect(route('posts.index'));
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
if($post->trashed()){
$post->deleteImage();
$post->forceDelete();
}else{
$post->delete();
}
session()->flash('success', 'Post deleted succesfully.');
return redirect(route('posts.index'));
}
/**
* Display a list of all trashed posts
*
* #return \Illuminate\Http\Response
*/
public function trashed(){
$trashed = Post::onlyTrashed()->get();
return view('posts.index')->withPosts($trashed);
}
public function restore($id){
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
$post->restore();
session()->flash('success', 'Post restored succesfully');
return redirect()->back();
}
}
Your $post->category is not an object which is why this error is coming.
Try
dd($post->category)
and you'll see what's in it. That will help you to debug the real problem.
First eager load the relation (to prevent N+1 issues) using:
public function index()
{
$posts = Post::with('category')->get();
return view('posts.index')->with('posts', $posts);
}
Then if you still get the error, it might be due to the fact that the post you are trying to view does not have category, so the relation is null. So when you try to get the category id, it throws that exception that null does not have id.
You can simply solve it by checking if there is any category before:
#if($post->category)
<a href="{{ route('categories.edit', $post->category->id ) }}">
{{ $post->category->name }}
</a>
#endif
Use eager loading in your controller before injecting the model to the view.
$post->load('category');
Make sure that each post has a relation with a category.
I received this error while trying to run two-layer loops in order to get a list out of an array:
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$event_parts
I wanted to produce a table where it lists all my events and at the same time there is a column that listed all the attending participants.
Here is the phpmyadmin table:
Here is my EventController:
<?php
namespace App\Http\Controllers;
use App\Models\Event;
use Illuminate\Http\Request;
class EventController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$events = Event::paginate(5);
return view('events.index', compact('events'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$events = Event::all();
return view('events.create', compact('events'));
##return view('events.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'event_name' => 'required',
'event_start' => 'required',
'event_end' => 'required',
'event_category' => 'required',
#'event_part' => 'required'
]);
Event::create($request->all());
return redirect()->route('events.index')
->with('success', 'Event added successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function show(Event $event)
{
return view('events.show', compact('event'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function edit(Event $event)
{
return view('events.edit', compact('event'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Event $event)
{
$request->validate([
'event_name' => 'required',
'event_start' => 'required',
'event_end' => 'required',
'event_category' => 'required'
]);
$event->update($request->all());
return redirect()->route('events.index')
->with('success', 'Event updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Event $event
* #return \Illuminate\Http\Response
*/
public function destroy(Event $event)
{
$event->delete();
return redirect()->route('events.index')
->with('success', 'Event deleted successfully');
}
}
Here is my migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEventsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->id('event_id');
$table->string('event_name');
$table->datetime('event_start');
$table->datetime('event_end');
$table->string('event_category');
$table->json('event_parts')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('events');
}
}
Here is my index.blade.php:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 CRUD </h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('events.create') }}" title="Create a event"> <i class="fas fa-plus-circle"></i>
</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered table-responsive-lg">
<tr>
<th>No</th>
<th>Event Name</th>
<th>Event Start</th>
<th>Event End</th>
<th>Event Category</th>
<th>Event Participants</th>
<th width="280px">Action</th>
</tr>
#foreach ($events as $event )
<tr>
<td>{{ ++$i }}</td>
<td>{{ $event->event_name }}</td>
<td>{{ $event->event_start }}</td>
<td>{{ $event->event_end }}</td>
<td>{{ $event->event_category }}</td>
<td> #foreach ($events->event_parts as $event_part) {{ $event_part }} #endforeach</td>
<td>
<form action="{{ route('events.destroy', $event->event_id) }}" method="POST">
<a href="{{ route('events.show', $event->event_id) }}" title="show">
<i class="fas fa-eye text-success fa-lg">View</i>
</a>
<a href="{{ route('events.edit', $event->event_id) }}">
<i class="fas fa-edit fa-lg">Edit</i>
</a>
#csrf
#method('DELETE')
<button type="submit" title="delete" style="border: none; background-color:transparent;">
<i class="fas fa-trash fa-lg text-danger">Delete</i>
</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $events->links() !!}
#endsection
I am trying to pull data from a different table into a select tag where the user can choose which program a certain course belongs to. I am getting an error of syntax error, unexpected '}', expecting ')' (View: C:\xampp\htdocs\IRMS\resources\views\courses\create.blade.php). How can I achieve this so that when I click on the Add Course button, it will give me the form iI can select the program code from.?
My code below:
index.blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<p>Go Back</p>
<div class="card">
<div class="card-header">Courses</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<p>Add Course</p>
#if (count($courses)> 0 )
<table class="table table-striped">
<tr>
<th></th>
<th>Program Code</th>
<th>Course Code</th>
<th>Course Name</th>
<th></th>
<th></th>
</tr>
#foreach ($courses as $course)
<tr>
<td></td>
<td>{{$course->program_code}}</td>
<td>{{$course->course_code}}</td>
<td>{{$course->course_name}}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
#endforeach
</table>
#else
<p>No Courses found!</p>
#endif
</div>
</div>
</div>
</div>
</div>
#include('inc.sadmin-navbar')
#endsection
create blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<p>Go Back</p>
<div class="card">
<div class="card-header">Add New Course</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
{!! Form::open(['action'=>'CoursesController#store', 'method'=>'POST']) !!}
<div class="form-group row justify-content-center">
{{Form::label('program_name', 'Program Name')}}
<div class="col-md-4">
#foreach ($programs as $program)
{{Form::select('{{$program->id}}', ['{{$program->program_code}}'], null, ['placeholder' => 'Pick Program'])}}
#endforeach
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::submit('Add Program', ['class'=>'btn btn-success'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#include('inc.sadmin-navbar')
#endsection
courses controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Course;
use App\Program;
class CoursesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$courses = Course::all();
return view('courses.index')->with('courses', $courses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$programs = Program::all();
return view('courses.create')->with('programs', $programs);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
programs controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Program;
// use App\CSE;
class ProgramsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$programs = Program::all();
return view('programs.index')->with('programs', $programs);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('programs.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'program_name' => 'required',
'program_code' => 'required'
]);
$program = new Program;
$program->program_name = $request->input('program_name');
$program->program_code = $request->input('program_code');
$program->save();
return redirect('home/programs');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$program = Program::find($id);
// $courses = CSE::all();
return view('programs.software.index')->with('program', $program);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$program = Program::find($id);
return view('programs.edit')->with('program', $program);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'program_name' => 'required',
'program_code' => 'required'
]);
$program = Program::find($id);
$program->program_name = $request->input('program_name');
$program->program_code = $request->input('program_code');
$program->save();
return redirect('home/programs');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$program = Program::find($id);
$program->delete();
return redirect('home/programs');
}
}
You don't have to use {{}} inside php form::select .
Try replacing the following lines .
#foreach ($programs as $program)
{{Form::select('{{$program->id}}', ['{{$program->program_code}}'], null, ['placeholder' => 'Pick Program'])}}
#endforeach
With this one : :
#foreach ($programs as $program)
{{Form::select($program->id, [$program->program_code], null, ['placeholder' => 'Pick Program'])}}
#endforeach
Try this and let me know, if you have any issues.
You can try this also
$programs = Program::all();
$select = [];
foreach($programs as $program){
$select[$program->id] = $program->program_code;
}
return view('programs.index', compact(['programs','select'));
{!! Form::select('program', $select, null, ['class'=>'form-control']) !!}
or
#foreach ($programs as $program)
{{Form::select($program->id, [$program->program_code], null, ['placeholder'=>'Pick Program'])}}
#endforeach
remove {{ }} in your code:
{{Form::select('{{$program->id}}', ['{{$program->program_code}}'], null, ['placeholder' => 'Pick Program'])}}
it just is:
$list_program is an array contain [program_id => program_code]
{!! Form::select('program_id', $list_program, null, ['placeholder' => 'Pick Program'])!!}
I have a form in which you submit a "project". One of the field is "created by", but the user does not update this, it gets the name of the authenticated user in that moment and inserts it into the db.
I know how to retrieve the user's name, but the problem is that when I login with another user, then all the name change, because I store the name each time.
This is my project controller
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Client;
use Auth;
use Illuminate\Http\Request;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('projects.index', [
'project' => Project::all()
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
if (Auth::user()->role != 1){
return redirect()->back();
}else{
return view('projects.create',[
'project' => new Project,
'client' => new Client
]);
}
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $r)
{
$validatedData = $r->validate([
'proj_title' => 'required|max:100',
'client_id' => 'required',
'proj_desc' => 'required',
]);
$currentUser = Auth::user()->name;
$r['created_by'] = $currentUser;
$project = Project::create($r->all());
return redirect('/projects')->with('store','');
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $r, Project $project)
{
$project->update($r->all());
return redirect('/projects')->with('update','');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
$project->delete();
return redirect('/projects')->with('delete','');
}
}
And this is my index
#section('content')
<div class="row">
<div class="col">
#if (Auth::user()->role == 1)
<a class="btn btn-success" href="/projects/create">Add Project</a>
#endif
</div>
<div class="col"></div>
<div class="col">
#if(session()->has('store'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project created</strong>
</div>
#elseif(session()->has('update'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project updated</strong>
</div>
#elseif(session()->has('delete'))
<div class="alert alert-success mt-2" role="alert">
<strong>Project deleted</strong>
</div>
#endif
</div>
</div>
<br>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Project Id</th>
<th>Title</th>
<th>Description</th>
<th>Client Id</th>
<th>Created by</th>
<th>Created on</th>
#if (Auth::user()->role==1)
<th>Admin</th>
#endif
</tr>
</thead>
<tbody class="">
#foreach ($project as $project)
<tr>
<td>{{$project->proj_id}}</td>
<td>{{$project->proj_title}}</td>
<td>{{$project->proj_desc}}</td>
<td>{{$project->client_id}}</td>
<td>{{$project->Auth::user()->name}}</td>
<td>{{$project->created_at}}</td>
#if (Auth::user()->role==1)
<td>
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="{{route('projects.edit',$project)}}">Edit</a>
<form method="POST" action="{{route('projects.destroy',$project)}}" onsubmit="return confirm('Are you sure you want to delete this?')">
#method('DELETE')
#csrf
<button class="dropdown-item" type="submit">Delete</button>
</form>
</div>
</div>
</td>
#endif
</tr>
#endforeach
</tbody>
</table>
#endsection
I think your problem is that you are using:
{{ $project->Auth::user()->name }}
instead of
{{ $project->created_by }}
I have this edit form and the back button is not working, So when I clicked the back button it shows this error,
This is the backbutton for my createOffice I tried applying it to my EditOffice backbutton and it didnt work:
Back
Also, how do I make the UpdateOffice button when clicked it goes back to the page for the list of offices I'm using return redirect()->back(); and it stays in the edit form page.. whats the right code for this?
Here are the codes
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','like','%'.$search.'%')->get();
return view('search')->with('offices', $offices)->with('search', $search);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($id)
{
return view('createoffice')->with('id', $id);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
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()->back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$office = Office::find($id);
return view('office')->withOffice($office);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$office = Office::find($id);
return view('editoffice')->withOffice($office)->with('id',$id);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$office = Office::find($id);
$office->name =$request->officename;
$office->floor = $request->floor;
$office->update();
\Session::flash('building_flash', 'Updated successfully!');
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$office = Office::find($id);
$office->delete();
\Session::flash('building_flash_delete', 'Deleted successfully!');
return redirect()->back();
}
}
PageController.php
class PageController extends Controller
{
public function buildings(){
$buildings = Building::paginate(10);
return view('buildings')->with('buildings', $buildings);
}
public function show($id){
$building = Building::find($id);
$offices = Office::where('building_id', $id)->orderBy('floor')->get();
return view('building')->with('building', $building)->with('offices', $offices);
} }
Building.blade.php
#extends('layouts.main')
#section('title',$building->name)
#section('css')
#stop
#section('content')
<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()!!}
<hr>
<table class="table">
<thead>
<th>Office Name</th>
<th>Office Floor</th>
</thead>
<tbody>
#foreach($offices as $office)
<tr>
<td>{{$office->name}}</td>
<td>{{$office->floor}}</td>
<td class="a">
#if(!Auth::guest())
Edit
Delete
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
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');
});
editoffice.blade.php
#extends('layouts.main')
#section('title', 'Create an Office')
#section('content')
{!! Form::open(array('route' => ['editoffice', $id], 'class' => 'form')) !!}
<div class="container">
<div class="form-group">
{!! Form::label('Office Name') !!}
{!! Form::text('officename', $office->name, array('required',
'class'=>'form-control',
'placeholder'=>'Office Name')) !!}
</div>
<div class="form-group">
{!! Form::label('Office Floor') !!}
{!! Form::text('floor', $office->floor, array('required',
'class'=>'form-control',
'placeholder'=>'Office Floor')) !!}
</div>
<div class="form-group">
{!! Form::submit('Update Office',
array('class'=>'btn btn-primary')) !!}
Back
</div>
{!! Form::close() !!}
#endsection
The main problem that I can see, is with your routes definitions and passing of parameters with nested routes. For example lets take edit office route;
Route::get('building/{id}/offices/edit', 'OfficeController#edit')->name('editofficeform');
This is actually a nested route which by definition should be expecting two parameters; (1) The building_id of the building you are editing, that you have specified as {id} (2) you should also pass the office_id, which will be the id of that specific office which you want to edit.
The correct route definition should be something like this;
Route::get('building/{id}/offices/{office_id}/edit', 'OfficeController#edit')->name('editofficeform');
And then on building.blade.php when you are specifying edit link like this;
Edit
It should be changed to this;
Edit
Here you will be passing the main building id and that specific office id which you can use however you want and can keep track of which building page you are on.
On controller side in OfficeController.php you can change your edit() action to this;
public function edit($id, $office_id)
{
$office = Office::find($office_id);
return view('editoffice')->withOffice($office)->with('id',$id);
}
Now you can use your same back button link on office edit form and it should work fine and should take you back to actual building page.
Back
I hope this explanation helps to solve the any other issues of this kind as well.
Update
As you have been having issue with other routes of this type. In editoffice.blade.php, you can update your form tag like this;
{!! Form::open(array('route' => ['editoffice', ["id"=>$id, "office_id"=>$office->id]], 'class' => 'form')) !!}
And in OfficeController.php update your update() method to handle this additional parameter;
public function update(Request $request, $id, $office_id)
{
$office = Office::find($office_id);
$office->name =$request->officename;
$office->floor = $request->floor;
$office->update();
\Session::flash('building_flash', 'Updated successfully!');
//return redirect()->back();
// You can replace this statement with the following to redirect the user to building page, rather than going back to edit form.
return redirect()->route('building', $id);
}
You can use same analogy in createoffice.blade.php and similarly in store() method. Of-course there won't be any office_id.