I have a difficulty displaying the view I created. I am studying laravel now and I found this useful article how to create a simple CRUD.
http://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
But I am stuck at displaying the first layout using the routes. Here's my code so far.
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function()
{
return View::make('hello');
});
Route::resource('nerd','NerdController');
Nerd.php (model)
<?php
class Nerd extends Eloquent
{
}
?>
NerdController.php (controller)
<?php
class NerdController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//get all nerds
$nerds = Nerd::all();
//load the view
return View::make('nerds.index')-
>with('nerds', $nerds);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return View::make('nerds.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
database setting
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'laravel_forums',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
index.blade.php (view)
<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li>View All Nerds</li>
<li>Create a Nerd
</ul>
</nav>
<h1>All the Nerds</h1>
<!-- will be used to show any messages -->
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Nerd Level</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($nerds as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->nerd_level }}</td>
<!-- we will also add show, edit, and delete buttons -->
<td>
<!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
<!-- we will add this later since its a little more complicated than the other two buttons -->
<!-- show the nerd (uses the show method found at GET /nerds/{id} -->
<a class="btn btn-small btn-success" href="{{ URL::to('nerds/' . $value->id) }}">Show this Nerd</a>
<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit -->
<a class="btn btn-small btn-info" href="{{ URL::to('nerds/' . $value->id . '/edit') }}">Edit this Nerd</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</body>
</html>
When I try to view the index using this path
http://mylocalhost/testsite/nerds
I got
Not Found
The requested URL /testsite/nerds was not found on this server.
That's all guys. I hope you can help me.
Assuming that app root URL is http://website.loc/testsite/ the solution is:
a: eighter access this URL thru web browser
http://mylocalhost/testsite/nerd
b:
// or change this
Route::resource('nerd', ...);
// to this
Route::resource('nerds', ...)
Simply you told Laravel to catch /nerd in URL but access /nerds instead. I am sure you got it now :)
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'm trying to upload image in mysql database, but in the banner_photo field "C:\xampp\tmp\phpE0A1.tmp" this .tmp file automatically generated every time. Please help to find what is the problem and what is the solution of it!
my index.blade.php file
#extends('admin.layout.master')
#section('content')
<div class="container-scroller">
<!-- partial:partials/_navbar.html -->
#include('admin.layout.nav')
<!-- partial -->
<div class="container-fluid page-body-wrapper">
<!-- partial:partials/_sidebar.html -->
#include('admin.layout.sidebar')
<!-- partial -->
<div class="main-panel">
<div class="content-wrapper">
<!-- Page Title Header Starts-->
<div class="row page-title-header">
<div class="col-12">
<div class="page-header">
<h4 class="page-title">Dashboard</h4>
</div>
</div>
</div>
<!-- Page Title Header Ends-->
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12 grid-margin">
<div class="card">
<div class="card-body">
<div class="d-flex justify-content-between">
<h4 class="card-title mb-0">Banner</h4>
<small>Show All</small>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est quod cupiditate esse fuga</p>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>H4 Title</th>
<th>H2 Title</th>
<th>Paragraph</th>
<th>Image</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach($banners as $row)
<tr>
<td>{{$row->id}}</td>
<td>{{$row->h4_title}}</td>
<td>{{$row->h2_title}}</td>
<td>{{$row->banner_paragraph}}</td>
<td>{{$row->banner_photo}}</td>
<td><button type="submit" class="btn btn-primary"><i class="fas fa-edit"></i>EDIT</button></td>
<td><button type="submit" class="btn btn-danger"><i class="far fa-trash-alt"></i>DELETE</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
<!-- partial:partials/_footer.html -->
#include('admin.layout.footer')
<!-- partial -->
</div>
<!-- main-panel ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
<!-- container-scroller -->
#endsection
my web.php file
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('index');
});
Route::get('/contact-us', function () {
return view('contactus');
});
Route::get('/tours', function () {
return view('tours');
});
// Admin panel Pages Routes
Route::get('/admin', function () {
return view('admin/index');
});
Route::get('/admin/bannercustomize', function () {
return view('admin/layout/bannercustomize');
});
// Controller routes
Route::post('store/banner','BannerController#store')->name('store.banner');
Route::get('/admin','BannerController#index')->name('admin.index');
my BannerController.php file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Banner;
use Image;
use Illuminate\Support\Str;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
class BannerController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$banners = Banner::all();
return view('admin.index',compact('banners'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.layout.bannercustomize');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'h4_title' => 'required',
'h2_title' => 'required',
'banner_paragraph' => 'required',
'banner_photo' => 'required'
]);
$banner = new Banner([
'h4_title' => $request->get('h4_title'),
'h2_title' => $request->get('h2_title'),
'banner_paragraph' => $request->get('banner_paragraph'),
'banner_photo' => $request->file('banner_photo')
]);
$request->banner_photo->store('public/image/banner_image/');
$banner->save();
return redirect()->back()->with('success', 'Data Added');
}
/**
* 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)
{
//
}
}
N.B: I'm using Laravel 7.x
When you upload a file, php will assign a temporary name and location (for example: C:\xampp\tmp\phpE0A1.tmp) until you locate it somewhere.
Usually what you save in the database is the location and the name of the file once it is located in a directory of your project
So, store the file first, and then save the path in the database:
public function store(Request $request)
{
$this->validate($request, [
'h4_title' => 'required',
'h2_title' => 'required',
'banner_paragraph' => 'required',
'banner_photo' => 'required|file'
]);
$path = $request->file('banner_photo')->store('public/image/banner_image');
$banner = new Banner([
'h4_title' => $request->get('h4_title'),
'h2_title' => $request->get('h2_title'),
'banner_paragraph' => $request->get('banner_paragraph'),
'banner_photo' => $path
]);
$banner->save();
return redirect()->back()->with('success', 'Data Added');
}
Or, since you are storing the file on public/ storage directory, you may use the public disk to store the file:
$path = $request->file('banner_photo')->store(
'image/banner_image', 'public'
);
Bonus:
You'll can access to it by the url on your index.blade table:
<table class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>H4 Title</th>
<th>H2 Title</th>
<th>Paragraph</th>
<th>Image</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach($banners as $row)
<tr>
<td>{{$row->id}}</td>
<td>{{$row->h4_title}}</td>
<td>{{$row->h2_title}}</td>
<td>{{$row->banner_paragraph}}</td>
<td><img src="{{ asset( Storage::url($row->banner_photo) ) }}" /></td>
<td><button type="submit" class="btn btn-primary"><i class="fas fa-edit"></i>EDIT</button></td>
<td><button type="submit" class="btn btn-danger"><i class="far fa-trash-alt"></i>DELETE</button></td>
</tr>
#endforeach
</tbody>
</table>
Note: Furthermore, you should create a symbolic link at public/storage which points to the storage/app/public directory.
References:
File Storage File Uploads.
File Storage The Public Disk.
File Storage File URLs.
I'm on the project in which I want to get the table in which record which I was trashed show and its working correctly and my trashed records are also show.
My logic of code is that when my trashed record are shown then in action field it show me only restore button otherwise in that field it show me two button of 'Delete' and 'Trash'. for this to work, when I apply this condition in my view file its return me this error which written in my title. #if($record->trashed())
resource controller
namespace App\Http\Controllers;
use App\sepCategory; use Illuminate\Http\Request;
class SepCategoryController extends Controller {
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$cat=sepCategory::all();
return view('cusCate',compact('cat'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* 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 \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function show(sepCategory $sepCategory)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function edit(sepCategory $sepCategory , $id)
{
$a= sepCategory::find($id);
return view('cusEdit',['data'=>$a]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function update(Request $request, sepCategory $sepCategory)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\sepCategory $sepCategory
* #return \Illuminate\Http\Response
*/
public function destroy(sepCategory $sepCategory,$id)
{
if ($sepCategory::find($id)->forceDelete()) {
return back()->with('message','record successfully delete');
} else {
return back()->with('error','record not delete');
}
}
public function trash()
{
$cat=sepCategory::onlyTrashed()->paginate(3);
return view('cusCate',compact('cat'));
}
public function remove($id)
{
$temp= sepCategory::find($id);
if ($temp->delete()) {
return back()->with('message','record successfully trashed');
}else{
return back()->with('error','can not correctly trashed');
}
}
public function recover($id)
{
} }
view blade file
view the trashed data
Category of student
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#elseif(session()->has('error'))
<div class="alert alert-danger">
{{ session()->get('error') }}
</div>
#else
#endif
<table>
<tr>
<th>Name</th>
<th>id</th>
<th>Phone</th>
<th>Roll no</th>
<th>Action</th>
<th>
#if ($cat->trashed())
Deleted At
#else
updated At
#endif
</th>
</tr>
#if (isset($cat))
#foreach ($cat as $item)
<tr>
<td>{{ $item->name }}</td>
<td>{{ $item->id }}</td>
<td>{{ $item->mobile_no }}</td>
<td>{{ $item->roll_no }}</td>
<td>
#if ($item->trashed())
Restore
#else
Edit
<form action="{{ url('/home/destroy') }}" method="post">
#csrf
{{ method_field('DELETE') }}
<input type="hidden" value="{{ $item->id }}" name="id">
<button type="submit">Delete</button>
</form>
<!-- this is trashed-->
Trashed
#endif
</td>
<td>
#if ($item->trashed())
{{ $item->deleted_at }}
#else
{{ $item->updated_at }}
#endif
</td>
</tr>
#endforeach
#endif
Error
Method Illuminate\Database\Eloquent\Collection::trashed does not exist. (View: D:\xamp\htdocs\project laravel\newTran\resources\views\cusCate.blade.php)
why it say trashed not exist
To begin with.. the trashed() method is avaiable if you are using the withTrashed() scope when doing your query. So, you'll need to add this (also notice that I replaced all() with get()):
# SepCategoryController.php
$cat = sepCategory::withTrashed()->get();
// ^^^^^^^^^^^^^^^^^^^^
return view('cusCate', compact('cat'));
Notice that this model must use the SoftDeletes trait.
Now, you are calling the trash() method on a Collection instance instead of on a model one. This is because $cat is a collection of sepCategory:
# SepCategoryController.php
$cat = sepCategory::withTrashed()->get();
return view('cusCate', compact('cat'));
<!-- In your view -->
<th>
#if ($cat->trashed()) // <---
Deleted At
#else
updated At
#endif
</th>
You should iterate over the elements of this collection in order to access individual models:
#foreach($cat as $category)
<th>
#if ($category->trashed()) // <---
Deleted At
#else
updated At
#endif
</th>
#endforeach
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
As the title suggests, I can't get the delete() option to work. I've struggled through a lot of posts online but the right answer just isn't there.
I'm using Laravel 5.5 with Homestead (installed a week ago, newest versions or so).
Let me give you some code and I really hope somebody is able to help me out.
This gives me a headache and the olanzapine is running out. Please tell me what I am doing wrong, and if there is something that's missing, please let me know!
I want to delete a page as a admin, but I Laravel doesn't seem to authorize me and gives me this error:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
This is my controller:
<?php
namespace App\Http\Controllers\Admin;
use Auth;
use App\Page;
use App\Http\Requests\WorkWithPage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class PagesController extends Controller
{
public function __construct() {
$this->middleware('admin');
$this->middleware('can:manageUsers,App\User');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (Auth::user()->isAdmin()) {
$pages = Page::paginate(20);
} else {
$page = Auth::user()->pages()->paginate(5);
}
return view('admin.pages.index', ['pages' => $pages]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.pages.create')->with(['model' => new Page()]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(WorkWithPage $request)
{
Auth::user()->pages()->save(new Page($request->only([
'title','url','content'])));
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangemaakt');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function edit(Page $page)
{
if(Auth::user()->cant('update', $page)){
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
}
return view('admin.pages.edit', ['model' => $page]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function update(WorkWithPage $request, Page $page)
{
if(Auth::user()->cant('update', $page)){
return redirect()->route('pages.index')->with('status', 'Dat mag jij niet');
}
$page->fill($request->only([
'title','url','content'
]));
$page->save();
return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Page $page
* #return \Illuminate\Http\Response
*/
public function destroy(Page $page)
{
if(Auth::user()->cant('delete', $page)){
return redirect()->route('pages.index')->with('status', 'Hey knul! Pssst! Wegwezen!');
}
$page->id->delete();
return redirect()->route('pages.index')->with('status', 'Page has been deleted.');
}
}
And this is my index page (index as in admin index for backend :
#extends('layouts.app') #section('content')
<div class="container">
#if (session('status'))
<div class="alert alert-info">
{{ session('status') }}
</div>
#endif
Nieuwe pagina
<br>
<br>
<table class="table">
<thead>
<tr>
<th>Naam</th>
<th>URL</th>
<th>Opties</th>
</tr>
</thead>
#foreach($pages as $page)
<tr>
<td>
{{ $page->title }}
</td>
<td>{{ $page->url }}</td>
<td class="text-right">
<a href="{{ route('pages.destroy', ['page' => $page->id])}}" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
data-form="delete-form">
Delete
</a>
</td>
</tr>
#endforeach
</table>
{{$pages->links()}}
</div>
<form id="delete-form" action="" methode="POST">
{{method_field('DELETE')}}
{!! csrf_field() !!}
</form>
#endsection
Then there the routes:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/admin', function() {
return view('admin.index');
})->middleware('admin');
Route::resource('/admin/pages', 'Admin\PagesController', ['except' => ['show']]);
Route::resource('/admin/blog', 'Admin\BlogController', ['except' => ['show']]);
Route::resource('/admin/users', 'Admin\UsersController', ['except' => ['create', 'store', '']]);
Route::get('/home', 'HomeController#index')->name('home');
Then the policy:
<?php
namespace App\Policies;
use App\User;
use App\Page;
use Illuminate\Auth\Access\HandlesAuthorization;
class PagePolicy
{
use HandlesAuthorization;
public function before($user, $ability) {
if ($user->isAdmin()) {
return true;
}
}
/**
* Determine whether the user can update the page.
*
* #param \App\User $user
* #param \App\Page $page
* #return mixed
*/
public function update(User $user, Page $page)
{
return $user->id = $page->user_id;
}
/**
* Determine whether the user can delete the page.
*
* #param \App\User $user
* #param \App\Page $page
* #return mixed
*/
public function delete(User $user, Page $page)
{
return $user->id = $page->user_id;
}
}
And finally the middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AccessAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->hasAnyRole(['Super Admin','Admin'])) {
return $next($request);
}
return redirect('login');
}
}
Update: fixed!
In the view I changed:
#foreach($model as $post)
<tr>
<td>
{{ $post->title }}
</td>
<td>{{ $post->user()->first()->name }}</td>
<td>{{ $post->slug }}</td>
<td class="text-right">
<a href="{{ route('blog.destroy', ['blog' => $post->id])}}" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
data-form="delete-form">
Delete
</a>
</td>
</tr>
#endforeach
</table>
{{$model->links()}}
</div>
<form id="delete-form" action="#" methode="POST">
{{ method_field('DELETE') }}
{!! csrf_field() !!}
</form>
To:
#foreach($pages as $page)
<tr>
<td>
{{ $page->title }}
</td>
<td>{{ $page->url }}</td>
<td class="text-right">
<form action="{{ route('pages.destroy', ['page' => $page->id]) }}" method="POST" class="btn btn-danger delete-link" >
<input type="submit" value="delete"/>
{{method_field('DELETE')}}
{!! csrf_field() !!}
</form>
</td>
</tr>
#endforeach
</table>
{{$pages->links()}}
Not sure where to start...
First the exception you are receiving is because you are sending wrong method to the url. (I never do it that way) but probably you are sending GET when you are expecting POST (with DELETE overwrite). You have wrong named "methode", it should be "method".
Next... not sure if this is gone work $page->id->delete();... maybe $page->delete().
As suggestion - maybe it will be better to use !can() instead of cant(). There is no difference, but cant() may confuse you in some point.
And I am glad to see someone using ->fill() method but you may come up on a small problem when dealing with checkboxes. Check this: https://github.com/LaraModulus/admin-core/blob/master/src/traits/HelpersTrait.php