Edit a form with Laravel Framework - php

I'm new to laravel and trying to learn using it. I created a little project for threads. Nothing special. The thing is, the function to edit something doesn't work and I cant see why. Maybe someone of you see the mistake?
thats my Routes:
Route::get('/index', 'Test\\TestController#index');
Route::get('/add', 'Test\\TestController#add');
Route::post('/test', 'Test\\TestController#store');
Route::get('/show/{id}', 'Test\\TestController#show');
Route::get('/show/{id}/edit', ['as' => 'edit', 'uses' => 'Test\\TestController#edit']);
Route::put('/show/{id}/edit', ['as' => 'editing', 'uses' => 'Test\\TestController#update']);
thats the important parts of the edit method:
public function edit($id) {
$thread = Thread::query()->findOrFail($id);
return view('test.edit', [
'thread' => $thread
]);
}
public function update($id, StoreRequest $request) {
$thread = Thread::query()->findOrFail($id);
$thread->fill($request->all());
$thread->save();
return redirect(action('Test\\TestController#show', [$thread->id]));
}
}
show.blade
#extends('master')
#section('content')
<div class="panel panel-primary">
<div class="panel-heading">
<div class="panel-title">
{{ $thread->thread }}
</div>
</div>
<div class="form-body">
<div class="form-group"><br>
<ul>
{{$thread->content }}<br><br>
{{$thread->created_at->format('d.m.Y H:i:s')}}
</ul>
</div>
</div>
<div class="panel-footer">
<div class="btn btn-primary">Thread bearbeiten</div>
</div>
</div>
#stop
edit blade ( formular where the text I want to add is in the textbox and the save button )
#extends('master')
#section('content')
{!! Former::horizontal_open()->method('PUT')->action(action("Test\\TestController#update", [$thread->id])) !!}
{!! Former::populate($thread) !!}
{!! Former::text('thread')->label('Thread') !!}
{!! Former::text("content")->label("Content") !!}
{!! Former::large_primary_submit('Save!') !!}
{!! Former::close() !!}
#stop
model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
ERROR MESSAGE :
No query results for model [App\Models\Thread\Thread].

Related

Laravel - The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to add an event on a calendar I have created, however I am getting the following error
The POST method is not supported for this route. Supported methods:
GET, HEAD
I have used the methods #csrf and {{ method_field('PUT') }} to no avail. I have also cleared route cache which did not help. Any help is much appreciated.
Routes:
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function(){
Route::middleware('can:manage-users')->group(function(){
Route::resource('/users', 'UsersController', ['except' => ['show']]);
Route::resource('/courses', 'CoursesController', ['except' => ['show']]);
});
Route::middleware('can:manage-calendar')->group(function(){
Route::get('events', 'EventsController#index')->name('events.index');
Route::post('/addEvents', 'EventsController#addEvent')->name('events.add');
});
})
index.blade.php
#extends('layouts.app')
#section ('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-14">
<div class="card">
<div class="card-header">Calendar</div>
<div class="card-body">
{!! Form::open(array('route' => 'admin.events.index', 'method' => 'POST', 'files' => 'true'))!!}
{{-- {{method_field('PUT') }}
#csrf --}}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12"></div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
{!! Form::label('event_name', 'Event Name:') !!}
<div class="">
{!! Form::text('event_name', null, ['class' => 'form-control']) !!}
{!! $errors->first('event_name', '<p class="alert alert-danger">:message</p>') !!}
</div>
#Collin, I have added the image below in relation to your question
The error actually explains the problem. The method POST is not supported for the route you're using. You are trying to post to the route: admin.events.index but you actually want to post to the route events.add.
Route::post('/addEvents', 'EventsController#addEvent')->name('events.add');
{!! Form::open(array('route' => 'admin.events.add', 'method' => 'POST', 'files' => 'true'))!!}
{{-- #csrf --}}
Adding to this awnser is a possible solution for the validator exception the OP has mentioned in the comments.
The validator not found error can possibly come from the following:
When adding the the following code:
public function addEvent(Request $request)
{
$validator = Validator::make($request->all(),
[ 'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required' ]);
if ($validator->fails())
{ \Session::flash('warning', 'Please enter the valid details'); return Redirect::to('admin.events.index')->withInput()->withErrors($validator);
Try adding:
use Illuminate\Support\Facades\Validator;
Just check your form action url route. You have to pass 'route('admin.events.add)' rather than 'route('admin.events.index')' and also dont use 'PUT' it will accept 'POST' as well.

(1/1) ReflectionException Error Class App\Http\Request\UpdateApplicantRequest does not exist

I am new to laravel and I am trying to update to profile of the user who logged in. The error says:
Class App\Http\Request\UpdateApplicantRequest does not exist
But I imported it in the top of my controller.
HomeController.php
<?php
namespace App\Http\Controllers\Applicant;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\ApplicantsRepository;
use Flash;
use Response;
use App\Models\Applicant;
use App\Http\Request\UpdateApplicantRequest;
class HomeController extends Controller
{
private $applicantRepository;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(ApplicantsRepository $applicantRepo)
{
$this->middleware('applicant');
$this->applicantsRepository = $applicantRepo;
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('applicant-dashboard.home');
}
public function edit($id)
{
//$applicant = $this->applicantRepository->findWithoutFail($id);
$applicant = Applicant::where('id',$id)->get()->last();
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicant', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.home'));
}
$input = $request->all();
$applicant = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.home'));
}
}
Here is the code in my routes:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
Route::patch('/put', 'HomeController#update')->name('applicant.update');
and the code in my blade file:
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
I am looking for help.
Thanks in Advance.
Firstly, you use wrong namespace of UpdateApplicantRequest.
Change:
use App\Http\Request\UpdateApplicantRequest;
To:
use App\Http\Requests\UpdateApplicantRequest;
Then, change your form from:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
to:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'post']) !!}
{!! method_field('patch') !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}

Laravel 5.4 How to update profile of applicant guest that is logged in

I am new to laravel and I want to let the user update his/her profile when logged in. I want to get the ID of the user when updating his/her profile but when I click on the edit view to pass the data using the id I got this error:
(1/1) ErrorException
Missing argument 1 for App\Http\Controllers\Applicant\HomeController::edit()
Here is the code to my controller:
public function edit($id)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicants', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.index'));
}
$input = $request->all();
$cashier = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.index'));
}
Here is the code in my routes file:
Route::get('/edit', 'HomeController#edit')->name('applicant.edit');
Here is the code in my blade file:
#extends('layouts.app')
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
You need to pass the id into your route:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
You pass the ID into web.php:
Route::get('edit/{ID}', 'HomeController#edit')->name('applicant.edit');

Laravel unknown column

I have a problem with this error:
https://pastebin.com/cgm5yq0P
This is my form:
https://pastebin.com/bSU5X5EC
This is my web.php (route controller):
Route::post('/komentarz', 'VideosController#postComment');
This is my VideoController postComment function:
https://pastebin.com/SYbEjB8H
This is my Comment model:
https://pastebin.com/SxHX6gTP
This is my User model comments function:
public function comments() {
return $this->hasMany('App\Comment');
}
This is my Video model comments function:
public function comments(){
return $this->belongsToMany('App\Comment')->withTimestamps();
}
And finally, Migration file named create_comments_table:
https://pastebin.com/2cHscQfq
My Routes:
https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong
Your foreign keys are wrong. Change your migration to this.
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
Edit : This adds the comment and attaches it to the video and user.
// model fillable property
protected $fillable = [
'text', 'user_id', 'video_id',
];
// route
Route::post('/film/{id}/komentarz', 'VideosController#postComment');
// controller method
public function postComment(CreateCommentRequest $request, $id)
{
$video = Video::findOrFail($id);
$video->comments()->create([
'text' => $request->text,
'user_id' => auth()->id(),
]);
return 'works';
}
// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
<div class="col-md-3 control-label">
{!! Form::label('text', 'Treść komentarza:') !!}
</div>
<div class="col-md-8">
{!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-3">
{!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
</div>
</div>
{!! Form::close() !!}
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use
protected guarded = [];
instead of using fillable array.

Products list not seen while editing, using form model binding in laravel 5.1

In my ecommerce project, I have Product and Carousel Model.
Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'code', 'name', 'description', 'special_note', 'sort', 'display', 'weight', 'enquiry'
];
public function carousels()
{
return $this->belongsToMany('App\Carousel')->withTimestamps();
}
}
Carousel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Carousel extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['name', 'display', 'sort'];
public function products()
{
return $this->belongsToMany('App\Product')->withTimestamps();
}
public function getProductListAttribute()
{
return $this->products->lists('id');
}
}
Here's the controller:
public function create()
{
$products = Product::lists('name', 'id');
return view('admin.carousels.create', compact('products'));
}
public function store(Request $request)
{
$carousel = Carousel::create($request->all());
$carousel->products()->attach($request->input('product_list'));
return redirect()->back();
}
public function edit($id)
{
$carousel = Carousel::findOrFail($id);
$products = Product::lists('name', 'id');
return view('admin.carousels.edit', compact('carousel', 'products'));
}
public function update(Request $request)
{
dd($request->all());
}
The carousel form:
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control input-sm', 'id' => 'name']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('sort', 'Sort:') !!}
{!! Form::text('sort', null, ['class' => 'form-control input-sm', 'id' => 'sort']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('display', 'Display:') !!}
{!! Form::select('display', ['Disabled' => 'Disabled', 'Enabled' => 'Enabled'], null, ['class' => 'form-control input-sm', 'id' => 'display']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::label('product_list', 'Products:') !!}
{!! Form::select('product_list[]', $products, null, ['class' => 'form-control input-sm', 'multiple']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::submit($submitButtonText, ['class' => 'btn btn-primary btn-block m_top_15', 'id' => $submitButtonId]) !!}
</div>
</div>
Now, the problem is that, when I use form model binding to edit the carousel form, I get no product displayed in the select box, though I can see all the products to select from. The selected products are not seen for the particular carousel.
What is the mistake that I have made ? Kindly help me out.
Thanks.
P.S: I am using Laravel 5.1 and came across this issue for the first time. Earlier I used to do this in Laravel 5 without any issue.
This may be related to how lists() is handled in 5.1. From the upgrade guide -
The lists Method
The lists method now returns a Collection instance instead of a plain
array for Eloquent queries. If you would like to convert the
Collection into a plain array, use the all method:
User::lists('id')->all(); Be aware that the Query Builder lists method
still returns an array.

Categories