How to render an uploaded image inside a view? - php

I am trying to get an image to upload and render when asked too.
I have successfully got the image upload working on my localhost, but once I push the code to the forge server, it breaks.
The image is uploaded however this is what I see once the post is created... See below.
I am not sure how to fix this issue.
Does anyone have any advice or suggestions on how to address this issue?
What I am doing wrong?
PostConroller
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('post.index', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$post = new Post(); // What is this?
return view('post.create', compact ('post'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$post = Post::create([
'user_id' => Auth::id(),
'title' => $request->title,
'body' => $request->body
]);
$this->storeImage($post);
return redirect('/posts');
}
/**
* Display the specified resource.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('post.show', compact('post'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('post.edit', compact('post'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$this->validatedRequest();
$post->update($request->except('image'));
$this->storeImage($post);
return redirect('/posts');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect('/posts');
}
private function validatedRequest()
{
return request()->validate([
'title' => 'required',
'body' => 'required',
'image' => 'sometimes|file|image|max:5000',
]);
}
private function storeImage($post)
{
if (request()->has('image')) {
$filename = Str::random(14).'.'.request()->image->getClientOriginalExtension();
$image = Image::make(request()->image)->fit(300, 300, null, 'top-left')->encode();
Storage::disk('public')->put("uploads/{$filename}", (string) $image);
$post->update([
'image' => "uploads/{$filename}"
]);
}
}
}
Form (show.blade.php)
#if($post->image)
<div class="row">
<div class="col-12">
<img src="{{ asset('storage/uploads/' . $post->image) }}" alt=""
class="img-thumbnail">
</div>
</div>
#endif

Files uploaded and stored via Storage can be accessed with the same Storage class. Try
<img src="{{ Storage::disk('public')->url('/uploads/' . $post->image) }}" alt=""
class="img-thumbnail">
asset() is used for accessing files in /public

Related

Create view in one controller and store data in other controller laravel

I'm new to Laravel and I'm trying to store a form. I created the view with the House controller but now I want to store the data in the view with the Booking controller. But when I click the button nothing happens.
My question is if it is possible to make a view with one controller and store it with another controller or maybe there is an other solution.
I also want to use the id of the house to store. How do I get that in the other controller as well?
Web Route
<?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('/', [\App\Http\Controllers\HouseController::class, 'index']);
Route::get('house/{house}', [\App\Http\Controllers\HouseController::class, 'show']);
Route::post('house/{house}', [\App\Http\Controllers\BookingController::class, 'store']);
Route::get('rental', [\App\Http\Controllers\HouseController::class, 'getUserHouses']);
Route::get('rental/new', [\App\Http\Controllers\HouseController::class, 'create']);
Route::post('rental/new', [\App\Http\Controllers\HouseController::class, 'store']);
Route::get('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'edit']);
Route::put('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'update']);
Auth::routes();
Booking controller
<?php
namespace App\Http\Controllers;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BookingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* 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)
{
$newBooking = Booking::create([
'user_id' => Auth::id(),
'house_id' => $request->id,
'begin' => $request->begin,
'end' => $request->end,
'status' => 0
]);
return redirect('/');
}
/**
* Display the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function edit(Booking $booking)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Booking $booking)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function destroy(Booking $booking)
{
//
}
}
House controller
<?php
namespace App\Http\Controllers;
use App\Models\house;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Helper\Imageable;
use DB;
class HouseController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$houses = House::all();
return view('/home', [
'houses' => $houses
]);
}
/**
* Display a listing of the houses the owner has
*
* #return \Illuminate\Http\Response
*/
public function getUserHouses()
{
$houses = DB::table('houses')
->where('user_id', '=', Auth::id())
->get();
return view('/rental/rental', [
'houses' => $houses
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('rental/new');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$newHouse = House::create([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'user_id' => Auth::id(),
'online' => $online,
'image' => $path,
]);
return redirect('rental');
}
/**
* Display the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function show(house $house)
{
return view(
'/house',
[
'house' => $house
]
);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function edit(house $house)
{
return view(
'rental/edit',
[
'house' => $house
]
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function update(Request $request, house $house)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$house->update([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'online' => $online,
'image' => $path,
]);
return redirect('rental/edit/' . $house->id);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function destroy(house $house)
{
//
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="display-one ">{{ $house->title }}</h1>
<p class=".text-light">{{ $house->place }}, {{ $house->country }}</p>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<img src="{{ asset("img/houses/$house->image") }}" alt="{{ $house->title }}" class="img-fluid" />
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Kies een datum en reserveer direct</label>
<form method="POST" action="">
#csrf
<input type="date" name="begin">
<input type="date" name="end">
<div class="col-md-12 bg-light mt-3">
<button type="button" class="btn btn-warning ml-2">Vraag aan</button>
</div>
</form>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-6">
<p class="display-one ">{{ $house->summary }}</p>
</div>
<div class="col-sm-6">
<h2 class="display-one ">Aangeboden door</h2>
<p>Prijs per nacht €{{ $house->price_per_night }}</p>
</div>
</div>
</div>
#endsection
First of all, nothing happens when you click the form submit button because it is currently type="button" and in order this button to play role of submission button it must be type="submit". You can do whatever you want with Laravel. If you want your form to hit another controller method you can simply specify that in your form tag. Like so:
Imagine this is a form inside a view that is rendered by HouseController
<form method="POST" action="{{ url('/save/from/booking/controller') }}">
// ....
</form>
And now on form submission inside a view that is rendered by HouseController, you will actually hit a route that is BookingController responsive for. And here is your route that is being hit by the form
Route::post('/save/from/booking/controller', [BookingController::class, 'store']);

Trying to get property of a non-object problem in laravel

I am working on a laravel project. In this project, if a non-user tries to edit a post then it will redirect to the posts page without letting the user make any edit. But I am getting this error
Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php).
ErrorException (E_ERROR) Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php) Previous exceptions and may be it might help Trying to get property of non-object (0) ErrorException {#221 ▼ #message: "Trying to get property of non-object" #code: 0 #file: "C:\xampp\htdocs\lsapp\storage\framework\views\b4b78b7a31531d4e8ddf98112cc09d54ba62ed99.php" #line: 3 #severity: E_NOTICE }
Here is the edit code:
public function edit($id)
{
$post = Post::find($id);
if(auth()->user()->id !== $post->user_id){
return redirect ('posts')->with('error','Unauthorized page');
}
return view('posts.edit')->with('post',$post);
}
PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use DB;
class PostsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except'=>['index','show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//$posts=Post::all();
//$posts=Post::orderBy('title','desc')->get();
//return Post::where('title','post two')->get();
//$posts=DB::select("SELECT * FROM posts");
//$posts= Post::orderBy('title','desc')->take(1)->get();
$posts= Post::orderBy('created_at','desc')->paginate(1);
return view('posts.index')->with('posts',$posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.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,[
'title'=>'required',
'body'=>'required'
]);
//Create posts
$post=new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->user_id=auth()->user()->id;
$post->save();
return redirect('posts')->with('success','Post Created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->with('post',$post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post = Post::find($id);
if(auth()->user()->id !== $post->user_id){
return redirect ('posts')->with('error','Unauthorized page');
}
return view('posts.edit')->with('post',$post);
}
/**
* 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,[
'title'=>'required',
'body'=>'required'
]);
//Create posts
$post=Post::find($id);
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('posts')->with('success','Post Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post=Post::find($id);
$post->delete();
return redirect('posts')->with('success','Post Deleted');
}
}
show.blade.php:
#extends('layouts.app')
#section('content')
Back
<h1>{{$post->title}}</h1>
<div>
{{$post->body}}
</div>
<hr>
#if(!Auth::guest())
#if(Auth::user()->id==$post->user_id)
<small>Witten on {{$post->created_at}} by {{$post->user->name}}</small>
<hr>
Edit
{!!Form::open(['action'=>['PostsController#destroy',$post->id],'method'=>'POST', 'class'=>'pull-right'])!!}
{{Form::hidden('_method','DELETE')}}
{{Form::submit('Delete',['class'=>'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
#endsection
here is my route:
Route::get('/index', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/services', 'PagesController#services');
Route::resource('/posts','PostsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
Here is user.php in case it helps
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany('App\Post');
}
}
Look in your blade file. Whenever you all $post->user->SOMEPROPERTIES, change it to $post->user['SOMEPROPERTIES']
Example:
<small>Witten on {{$post->created_at}} by {{$post->user['name']}}</small>
I hope it will work for you. (Working in my case)
Look in your blade file.
Whenever you all $post->user->SOMEPROPERTIES, change it to $post->user()
like here:
<small>Witten on {{$post->created_at}} by {{$post->user()->name}}</small>
check your href value. Check the curly braces
Wrong code:
#foreach($posts as $post)
the text of the link
#endforeach
Working code:
#foreach($posts as $post)
the text of the link
#endforeach
I hope this helps in some way.

Laravel Spatie unable to restrict UserController

Currently I have users.index blade which I would like to restrict. However, I failed to restrict it.
I have tried to create another test blade and a TestController and I have set permission to it and it works fine.
However with UserController, there is just no way to restrict Users from accessing it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
class TestController extends Controller
{
/**
* Restricting pages
*/
public function __construct()
{
$this -> middleware('permission:test-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('test.index');
}
/**
* 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($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)
{
//
}
}
views/test/index.blade.php
#extends('layouts.app')
#section('content')
<p>Testing Page</p>
#endsection
These are the results if I don't permit a particular user role to access this page.
enter image description here
enter image description here
So the above is the correct behavior.
However when it comes to user.index , I applied the same technique in the constructor of the UserController but it doesn't work
app/Http/Controllers/UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
class UserController extends Controller
{
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::orderBy('id','DESC') -> paginate(5);
return view('users.index' , compact('data')) -> with('i' , ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$roles = Role::pluck('name','name') -> all();
return view('users.create',compact('roles'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request -> all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User created successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return view('users.show',compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$roles = Role::pluck('name','name') -> all();
$userRole = $user->roles -> pluck('name','name') -> all();
return view('users.edit',compact('user','roles','userRole'));
}
/**
* 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, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if( ! empty($input['password'])) {
$input['password'] = Hash::make($input['password']);
} else {
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user -> update($input);
DB::table('model_has_roles') -> where('model_id',$id) -> delete();
$user -> assignRole($request -> input('roles'));
return redirect() -> route('users.index') -> with('success','User updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id) -> delete();
return redirect() -> route('users.index') -> with('success','User deleted successfully');
}
}
Result [I am still able to view this Blade in front end despite not having the permission to view this page]
enter image description here
This is my role-has-permission tablerole-has-permission
This is my role table
role
This is my permission table
permissions
This is my model-has-roles table model-has-roles
This is my model-has-permissions table model-has-permissions
If you want to restrict specific routes or all you can do something like this:
Route::middleware(['auth', 'permission:user-list'])->group(function (){
Route::get('/create', 'WelcomeController#create')->name('welcome');
...
...
..
});
or you can replace
public function construct()
{
$this -> middleware('permission:user-list', ['only' => ['index']]);
}
to
public function construct()
{
$this -> middleware('permission:user-list')->except(['index']);
}

Why hyperlinks for download PDF not working ? (no file)

I developed system for creating articles, each post except title and content consist possibility for uploading PDF.File names are stored in the database and they are written on the hyperlinks necessary to download the file.Now the problem is that when I want to download the file, it shows me a mistake in the browser.
Did anyone knows what is a problem ?
Database
Location of PDF files
result
Posts Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//including post model to controller
use App\Post;
//if we want to use sql syntax for queries
use DB;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//list articles by desc row
$posts= Post::orderby('created_at', 'desc')->paginate(3);
return view('posts.index')-> with('posts', $posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.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,[
'title' => 'required',
'content' => 'required'
]);
// Handle File Upload
if($request->hasFile('image')){
// Get filename with the extension
$filenameWithExt = $request->file('image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('image')->storeAs('public/upload', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
//create new post
$post= new Post;
$post -> title = $request -> input('title');
$post -> content = $request -> input('content');
$post->file_name = $fileNameToStore;
$post -> save();
return redirect('/posts') ->with('success', 'Post Created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//list post while we enter through link
$post= Post::find($id);
return view('posts.show')-> with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$post= Post::find($id);
return view('posts.edit')-> with('post', $post);
}
/**
* 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,[
'title' => 'required',
'content' => 'required'
]);
//create new post
$post= Post::find($id);
$post -> title = $request -> input('title');
$post -> content = $request -> input('content');
$post -> save();
return redirect('/posts') ->with('success', 'Post Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post= Post::find($id);
$post -> delete();
return redirect('/posts') ->with('success', 'Post Removed');
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<h1>{{$post->title}}</h1>
<div>
{{$post->content}}
</div>
<p><a href="./storage/app/public/upload/{{$post->file_name}}" download>Download the pdf</a></p>
<small>Written on {{$post->created_at}}</small>
Return
#endsection
Migration Create Post
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->mediumText('content');
$table->string('file_name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
storage/app/public is not visible to the user
You need to either move to public/... and/or create a symbolic link using this instructions: https://laravel.com/docs/5.7/filesystem#the-public-disk
php artisan storage:link
Then you replace
<a href="./storage/app/public/upload/{{$post->file_name}}" download>
With
<a href="{{asset('storage/upload/'.$post->file_name)}}" download>

Laravel: Trouble with update db after click button

I have problem: I build an app and I have 2 tables in my db: habits and users. The User has a field called points and after click a button 'Add point' I want to increment that value. I added a method in HabitsController called addPoints and button in a view, but I get an error message: MethodNotAllowedHttpException No message. There is my code.
HabitsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Habit;
use App\User;
use DB;
use App\Quotation;
class HabitsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//store in $habits all posts of current user
$habits = DB::table('habits')->where('user_id', auth()->id())->get();
return view('habits.index')->with('habits', $habits);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('habits.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, [
'name'=>'required',
'description'=>'required',
'difficulty'=>'required'
]);
$habit = new Habit;
$habit->name = $request->input('name');
$habit->description = $request->input('description');
$habit->difficulty = $request->input('difficulty');
$habit->NumberOfCompleted = 0;
$habit->user_id = auth()->user()->id;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$single = Habit::find($id);
return view('habits.show')->with('single', $single);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$single = Habit::find($id);
return view('habits.edit')->with('single', $single);
}
/**
* 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, [
'name'=>'required',
'description'=>'required',
'difficulty'=>'required'
]);
$habit = Habit::find($id);
$habit->name = $request->input('name');
$habit->description = $request->input('description');
$habit->difficulty = $request->input('difficulty');
$habit->NumberOfCompleted = 0;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$single = Habit::find($id);
$single->delete();
return redirect('/habits')->with('success', 'Habit deleted');
}
public function addPoint(Request $request, $id)
{
$habit = User::find($id);
$habit->points += 1;
$habit->save();
return redirect('/habits')->with('success', 'Habit created');
}
}
show.blade.php
#extends('layouts/app')
#section('content')
<div class="row single">
<div class="col-sm-8 col-sm-offset-2 showSingleHabit">
<h2>{{$single->name}}</h2>
<p>{{$single->description}}</p>
<p>{{$single->difficulty}}</p>
<p>{{$single->NumberOfCompleted}}</p>
Edit
{!!Form::open(['action' => ['HabitsController#destroy', $single->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
{!!Form::open(['action' => ['HabitsController#update', $single->id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'POST')}}
{{Form::submit('Add point', ['class' => 'btn btn-primary'])}}
{!!Form::close()!!}
</div>
</div>
#endsection
routes/web.php
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::resource('habits', 'HabitsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
I will be grateful for any help. :)
Change
{{Form::hidden('_method', 'POST')}}
To
{{Form::hidden('_method', 'PUT')}}

Categories