I am working on a library application and I want to create a function where the user can rent out a book to a customer. However, I want the books that are rented out right now to not show up in the select box when renting out another book.
I have looked up several articles about this, but couldn't really make up a solution so I would be happy about any help.
The idea is, that when a book has the attribute "maxreturndate" set it won't show up.
CheckedOutController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CheckedOut;
use App\Book;
use App\Reader;
class CheckedOutController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$checkedOuts = CheckedOut::with(['book', 'reader'])->get();
return view('checkedouts/index', compact('checkedOuts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$books = Book::all();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'book_id' => 'required',
'reader_id' => 'required',
'maxreturndate' => 'required|date',
'returndate' => 'nullable',
]);
$checkedOut = CheckedOut::create($validatedData);
return redirect('checkedouts')->with('success', 'Buch wurde erfolgreich verliehen!');
}
/**
* 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)
{
//
}
}
index.blade.php
#extends('layout')
#section('title')
<title>Alle ausgeliehen Bücher</title>
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="uper">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div><br />
#endif
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Titel</td>
<td>Verliehen an</td>
<td>Verleihdatum</td>
<td>Fällig am</td>
<td>Zurückgebracht am</td>
<td colspan="2">Funktionen</td>
</tr>
</thead>
<tbody>
#foreach($checkedOuts as $checkedOut)
<tr>
<td>{{$checkedOut->id}}</td>
<td>{{$checkedOut->book->title}}</td>
<td>{{$checkedOut->reader->name}}</td>
<td>{{$checkedOut->created_at}}</td>
<td >{{$checkedOut->maxreturndate}}</td>
<td>{{$checkedOut->returndate}}</td>
<td></td>
<td>Bearbeiten</td>
<td>Anzeigen</td>
<td>
<form action="{{ route('checkedouts.destroy', $checkedOut->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Löschen</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
<div>
#endsection
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCheckedOutsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('checked_outs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->bigInteger('reader_id')->unsigned();
$table->foreign('reader_id')->references('id')->on('readers')->onDelete('cascade');
$table->date('maxreturndate');
$table->date('returndate')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('checked_outs');
}
}
create.blade.php
#extends('layout')
#section('title')
<title>Buch verleihen</title>
#section('stylesheets')
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
#endsection
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="card uper">
<div class="card-header">
Buch verleihen
</div>
<div class="card-body">
<form method="post" action="{{ route('checkedouts.store') }}">
<div class="form-group">
#csrf
<label for="book_id">Buch:</label>
<select name="book_id" class="form-control select2-single <!-- #error('book_id') is-invalid #enderror -->">
#foreach ($books as $book)
<option value="{{ $book->id }}">{{ $book->title }}</option>
#endforeach
</select>
#error('book_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="reader_id">Verleihen an:</label>
<select name="reader_id" class="form-control select2-single <!-- #error('reader_id') is-invalid #enderror -->">
#foreach ($readers as $reader)
<option value="{{ $reader->id }}">{{ $reader->name }}</option>
#endforeach
</select>
#error('reader_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="maxreturndate">Zurückbringen bis:</label>
<input type="date" class="form-control" name="maxreturndate" />
#error('name')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Verleihen</button>
</form>
</div>
</div>
<script type="text/javascript">
$(".select2-single").select2();
</script>
#endsection
The relationship between the 3 Models:
Book:
public function checkedOut(){
return $this->hasOne(CheckedOut::class);
}
Reader:
public function checkedOut()
{
return $this->belongsTo(CheckedOut::class);
}
CheckedOut:
public function book(){
return $this->belongsTo(Book::class);
}
public function reader(){
return $this->belongsTo(Reader::class);
}
My suggestion is to set up Books and Readers with a many-to-many relationship. Now, your models could look like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Book extends Model
{
public function readers()
{
return $this
->belongsToMany(\App\Reader::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Reader extends Model
{
public function books()
{
return $this
->belongsToMany(\App\Book::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Checkout extends Pivot
{
// this should be named `book_reader` but we override it here
$table = "checked_outs";
$dates = [
"maxreturndate",
"returndate",
];
}
I have created a pivot model which isn't necessary, but allows you to operate directly on the pivot table and cast the extra attributes to dates automatically. Whether this is useful is a matter of opinion. You should rename the checked_outs table to book_reader which is the naming convention that Laravel expects for a pivot table.
Getting the books that aren't checked out is simple enough to do as follows, using the doesntHave method to check for absence of a relationship.
public function create()
{
$books = Book::doesntHave("readers")->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
And "checking out" a book could look like this:
public function store(Request $request)
{
$reader = Reader::find($request->reader_id);
$reader
->books()
->attach(
$request->book_id,
["returndate" => Carbon\Carbon::now()->addDays(7)]
);
}
when a book has the attribute "maxreturndate" set it won't show up
Since you did not specify in your migration, I am going to assume here that you have a maxreturndate nullable field in your books table, then you should be able to simply create a local scope when you want your list of "not rented" books.
Here's an example on creating a notRented scope:
// in your Book model define the local scope
public function scopeNotRented($query){
return $query->whereNotNull('maxreturndate');
}
// in the create method of your controller
public function create()
{
$books = Book::notRented()->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
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've been trying to get past this error for almost 2 days now. Needless to say, I'm still pretty new to Laravel. I'm using the Laravel's registration form (with some modifications) and I'm storing that User data in a table called "customusers" in my Database. That data includes their name/email/gender/description etc. And I'm trying to use a Resource Controller to basically print and edit that data. The problem I'm facing is, whenever I try to echo the data on my main page, it gives me the error "Property [id] does not exist on this collection instance" or email/name. But when I echo the data with Auth::user()->id, it works. And that's fine, it's do-able if I only wanted to echo data. But I also want to edit that data and I'm gonna have to use my Model for that. So following is my code:
Display.blade.php:
<div id="wrapper">
<div id="content">
<div id="card">
<div id="front">
<div id="top-pic"></div>
<div id="avatar"><span style="position: absolute;padding-top: 17px;margin-left: 34px;color: #fff;font-size: 64px;" class="h5">
{{ Auth::user()->name[0] }}
</span></div>
<div id="info-box">
<div class="info">
<h1>{{ Auth::user()->name }}</h1>
<h2>{{ Auth::user()->message }}</h2>
</div>
</div>
<div id="social-bar">
<a href="{{ Auth::user()->facebook }}" target="_blank">
<i class="fa fa-facebook"></i>
</a>
<a href="{{ Auth::user()->twitter }}" target="_blank">
<i class="fa fa-twitter"></i>
</a>
{{ link_to_route('display.edit','',[$customusers->id],['class'=>'fa fa-edit']) }}
</div>
</div>
Edit.blade.php:
{!! Form::model($customusers,array('route'=>['display.store',$customusers->id],'method'=>'PUT')) !!}
<div class="form-group">
{!! Form::text('name',null,['class'=>'form-control','placeholder'=>'Name']) !!}
</div>
<div class="form-group">
{!! Form::email('email',null,['class'=>'form-control','placeholder'=>'Email']) !!}
</div>
<div class="form-group form-row">
<div class="col-5">
{!! Form::select('gender', ['Male' => 'Male', 'Female' => 'Female'], null, ['class'=>'form-control','placeholder'=>'Choose Gender']); !!}
</div>
<div class="col">
{!! Form::text('facebook',null,['class'=>'form-control','placeholder'=>'Facebook ID']) !!}
</div>
<div class="col">
{!! Form::text('twitter',null,['class'=>'form-control','placeholder'=>'Twitter Handle']) !!}
</div>
</div>
<div class="form-group">
{!! Form::textarea('message',null,['class'=>'form-control','placeholder'=>'Talk about yourself']) !!}
</div>
<div class="form-group">
{!! Form::button('Create',['type'=>'submit','class'=>'btn btn-danger col-lg-12']) !!}
</div>
{!! Form::close() !!}
ProfileController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CustomUser;
use Illuminate\Support\Facades\DB;
class ProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$customusers = CustomUser::all();
return view ('display',compact('customusers'));
}
/**
* 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 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(CustomUser $customusers)
{
return view ('edit',compact('customusers'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, CustomUser $customusers)
{
$customusers->update($request->all());
return redirect()->route('display.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
CustomUser.php (Model):
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
protected $table = 'customusers';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','username','email','gender','password','message','twitter','facebook',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Web.php (Routes):
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::resource('/display','ProfileController');
So as you can see, I'm using compact in index() function to feed it all the user data in my database, and when I dd($customusers) - it does show me the data in array. But when I use {{ $customusers->name }} - it gives me an error saying "Property [name] does not exist on this collection instance". And thus, the same occurs whenever I try to use link_to_route('display.edit','',[$customusers->id],'') for redirecting the user to the Edit page. Please help me see what I'm doing wrong here. I previously made a CRUD app and I basically did the same things and it all worked perfectly. So I'm not understanding what the problem here is..
You need to loop customers data:
#foreach($customusers as $customer)
{{ link_to_route('display.edit','',[$customer->id],['class'=>'fa fa-edit']) }}
#endforeach
Or you can edit the current logged in data.
{{ link_to_route('display.edit','',[Auth::user()->id],['class'=>'fa fa-edit']) }}
$customusers->all() return a Collection (array of models)
$customers = [ {}, {}, {}, {} ]
So when you try to get the property name or any other it's undefined
You need to loop throw in the view:
#foreach($customusers as $customer)
// Here you have access to all Properties of each $customer
#endforeach
Basically you are passing all users ( collection of data ) to the view by compact.
you've to use foreach loop to access those data.
try loop through in view
#foreach($customusers as $customuser)
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
#endforeach
it will work
As I see your display blade file. You want to edit that user who is Authenticate.Auth
So that point you need to use FindOrFail() method in your controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CustomUser;
use Illuminate\Support\Facades\DB;
use Auth;
class ProfileController extends Controller
{
public function index()
{
$id = Auth::user()->id;
$customusers = CustomUser::FindOrFail($id);
return view ('display',compact('customusers'));
}
}
And Use display.blade.php file like:
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
Of if you want to return all the data then use below code:
#foreach($customusers as $customuser)
#if($customuser->id == Auth::user()->id);
{{ link_to_route('display.edit','',[$customuser->id],['class'=>'fa fa-edit']) }}
#endif
#endforeach
The controller as it is:
public function index()
{
$customusers = CustomUser::all();
return view ('display',compact('customusers'));
}
So I'm trying to create a Video store of sorts in which you can see the image of the movie, title, length and the option to delete it. The problem is when I try to upload an image it always returns null. Also I use Laravel 5.8.35
I tried with getClientOriginalExtension but it can't work since file returns null
Slika means Image
Žanr means Genre
Naslov means Title
Godina means Year
Filmovi means Movies
Trajanje means Lenght
Akcija means Action
index.blade.php
<style>
table,tr,td {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 800px;
font-size: 30px;
font-weight: bold;
text-align: center;
align-self: center;
}
</style>
<table>
<tr style="background-color:lightgray">
<td>Slika</td>
<td>Naslov filma</td>
<td>Godina</td>
<td>Trajanje</td>
<td>Akcija</td>
</tr>
#foreach($filmovi as $film)
<tr>
<td><img src="{{ $film->slika }}" alt="{{$film->slika}}"></td>
<td>{{ $film->naslov }}</td>
<td>{{$film->godina}}</td>
<td>{{$film->trajanje}} minuta</td>
<td> [obriši]</td>
</tr>
#endforeach
<div class="">
Dodaj novi film
</div>
create.blade.php
<div>
<form action="{{ route('filmovi.store') }}" method="post">
Naslov: <br>
<input type="text" class="form-control" id="naslov" name="naslov">
<br>
Žanr: <div class="select">
<select name="zanr" id="zanr">
#foreach($zanr as $z )
<option value="{{ $z->id }}">{{ $z->naziv }}</option>
#endforeach
</select>
</div>
Godina: <div class="select" style="width:200px;">
<select name="godina" id="godina">
#for($i = (int)date("1900"); $i<=(int)date("Y"); $i++)
<option value="{{ $i }}" name="godina" >{{ $i }}</option>
#endfor
</select>
</div>
Trajanje: <br>
<input type="text" class="form-control" id="trajanje" name="trajanje">
<br>
Slika: <br>
<form action="{{ route('filmovi.store') }}" method="post" enctype="multipart/form-data">
<input type="file" name="slika" class="form-control" enctype="multipart/form-data">(max. 64 KB)
<div class="form-group">
Natrag
<button type="submit" class="btn btn-success float-right">Objavi</button>
</div>
</form>
</form>
</div>
controller
<?php
namespace App\Http\Controllers;
use App\Filmovi;
use App\Zanr;
use Illuminate\Http\Request;
use App\Traits\UploadTrait;
class FilmoviController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
use UploadTrait;
public function index()
{
$filmovi = Filmovi::all();
return view('filmovi.index', compact('filmovi'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$zanr = Zanr::all();
return view('filmovi.create', compact('zanr'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$filmovi = Filmovi::create([
'naslov' => request('naslov'),
'id_zanr' => request('zanr'),
'godina' => request('godina'),
'trajanje' => request('trajanje'),
'slika' => request('slika'),
]);
if($request->has('slika'))
{
dd($slike = $request->file("slika"));
$dirpath = '/uploads/slike/';
$path=$dirpath . $slike;
$this->uploadOne($slike, $dirpath, 'public');
$filmovi->slika = $path;
}
$filmovi->save();
return redirect()->route('filmovi.index');
}
/**
* Display the specified resource.
*
* #param \App\Filmovi $filmovi
* #return \Illuminate\Http\Response
*/
public function show(Filmovi $filmovi)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Filmovi $filmovi
* #return \Illuminate\Http\Response
*/
public function edit(Filmovi $filmovi)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Filmovi $filmovi
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Filmovi $filmovi)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Filmovi $filmovi
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$filmovi = Filmovi::find($id);
$filmovi->delete();
// \Mail::to($post->user)->send(new PostDeleted($post));
return redirect()->route('filmovi.index');
}
}
UploadTrait
<?php
namespace App\Traits;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
trait UploadTrait
{
public function uploadOne(UploadedFile $uploadedFile, $dirpath = null, $disk = 'public')
{
$file = $uploadedFile->storeAs($dirpath, $uploadedFile,$disk);
return $file;
}
}
?>
As far as I can see there are two possibilities:
1. pass csrf-token in your form
2. add enctype="multipart/form-data" to your form.
Moreover you should save it to your storage and link it using symlink (use command php artisan storage:link) check the docs: https://laravel.com/docs/5.8/filesystem
After 'php artisan serve' command, the page like 'localhost:8000/biodata' opens and when I click on some link to go to the other page, the current page keeps on loading all the time without giving me any error. When I tried to change the server ports like'localhost:8080/biodata' and then click on the link immediately, the next page opens but the links on the next page doesn't work and the page keeps on loading until I again change the server ports.
I'm practicing with this online version of code from any other link. Here is the code.
index.blade.php:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h3>List Biodata Siswa</h3>
</div>
<div class="col-sm-2">
<a class="btn btn-sm btn-success" href="{{ route('biodata.create') }}">Create New Biodata</a>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<table class="table table-hover table-sm">
<tr>
<th width = "50px"><b>No.</b></th>
<th width = "300px">Name</th>
<th>Location</th>
<th width = "180px">Action</th>
</tr>
#foreach ($biodatas as $biodata)
<tr>
<td><b>{{++$i}}.</b></td>
<td>{{$biodata->name}}</td>
<td>{{$biodata->location}}</td>
<td>
<form action="{{ route('biodata.destroy', $biodata->id) }}" method="post">
<a class="btn btn-sm btn-success" href="{{route('biodata.show',$biodata->id)}}">Show</a>
<a class="btn btn-sm btn-warning" href="{{route('biodata.edit',$biodata->id)}}">Edit</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $biodatas->links() !!}
</div>
#endsection
web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
route::resource('biodata','BiodataController');
BiodataController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Biodata;
class BiodataController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$biodatas=Biodata::latest()->paginate(5);
return view('biodata.index',compact('biodatas'))
->with('i',(request()->input('page',1)-1)*5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('biodata.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'location'=>'required'
]);
Biodata::create($request->all());
return redirect()->route('biodata.index')
->with('success','new biodata created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$biodata = Biodata::find($id);
return view('biodata.detail', compact('biodata'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$biodata = Biodata::find($id);
return view('biodata.edit', compact('biodata'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'location' => 'required'
]);
$biodata = Biodata::find($id);
$biodata->name = $request->get('name');
$biodata->location = $request->get('location');
$biodata->save();
return redirect()->route('biodata.index')
->with('success', 'Biodata siswa updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$biodata = Biodata::find($id);
$biodata->delete();
return redirect()->route('biodata.index')
->with('success', 'Biodata siswa deleted successfully');
}
}
No error messages but the page keeps on loading.
There is typo error in your web.php file. The last line is
route::resource('biodata','BiodataController');
It should be
Route::resource('biodata','BiodataController');
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