Laravel 5.4 How to fix 'No query results for model' - php

Whenever I try to access /skills/add through an anchor in another page I get this error
The anchor that redirects to this page(with GET method) is:
<a class="btn icon-btn btn-success" href="/skills/add">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
Tried using dd("test") to test it out but won't even work.
This are my routes for skills/add this:
Route::put('/skills/add', 'SkillsController#add');
Route::get('/skills/add', 'SkillsController#addIndex');
Here are my functions in SkillsController
public function addIndex() {
if (Auth::check()) {
return view('skills.add');
} else {
return redirect('/home');
}
}
public function add(Request $request) {
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
$validator = Validator::validate($request->all(), $skillRules);
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
the skills.add view is this
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="/skills/add">
{{method_field('PUT')}}
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input name="name" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection

Not sure what happened, if someone in the future has this same problem, I literally just deleted and made manually thee controller, model and blade and it started to work. Not a lot of science or explain, sorry for that.

Change your route to named ones
Route::GET('/skills/add', 'SkillsController#addIndex')->name('addSkills');
Route::POST('/skills/add', 'SkillsController#add')->name('saveSkills');
and your blade to
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="{{route('saveSkills')"> //** Change this
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input type="text" name="name" class="form-control"> //** Change this
</div>
</div>
//Remaining form groups
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Change your anchor tag's href value to named route like
<a class="btn icon-btn btn-success" href="{{route('addSkills')}}">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
and your controller
// SHOW ADD NEW SKILL FORM
public function addIndex() {
if (Auth::check()) {
return view('skills.add'); //view path is skills->add.blade.php
} else {
return redirect('/home');
}
}
//SAVE ADD NEW SKILL FORM DATA
public function add(Request $request) {
dd($request->name); //Check if value is getting
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
$validator = Validator::validate($request->all(), $skillRules);
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
also add use App\RampUp\Skills; on top of controller

Sorry but there is no POST-route for <form method="POST" action="/skills/add">
maybe the POST is still executed.
On the other hand most Route errors could be resolved by clearing the cache (if present), rearranging the routes or put a group in between like
Route::group(['prefix' => 'skills'], function() {
Route::put('/add', 'SkillsController#add');
Route::get('/add', 'SkillsController#addIndex');
}

Related

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

Good evening , for school i am trying to create a simple CRUD app, using laravel 6 and mongoDB.
I can get read, update and delete working but creat fails with The POST method is not supported for this route. Supported methods: GET, HEAD.. I have searched the answers here and other sites but im stuck for 2 days now (could be something very silly but im not seeing it)
my routes are:
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/post/{_id?}', 'PostController#form')->name('post.form');
Route::post('/post/save/', 'PostController#save')->name('post.save');
Route::put('/post/update/{_id}', 'PostController#update')->name('post.update');
Route::get('/post/delete/{_id}', 'PostController#delete')->name('post.delete');
form.blade is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Post Form</div>
<div class="card-body">
#if($data)
<form action = "{{Route ('post.update', $data->_id)}}" method="post">
#csrf
#method('PUT')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content">{{$data->content}}</textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#else
<form action = "{{Route ('post.form')}}" method="post">
#csrf
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content"></textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#endif
</div>
</div>
</div>
</div>
#endsection
and my PostController is:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function form($_id = false){
if($_id){
$data = Post::findOrFail($_id);
}
$data = false;
return view ('post.form', compact('data'));
}
public function save (Request $request){
$data = new Post($request->all());
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function update (Request $request, $_id){
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->save();
/* return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]); */
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function delete($_id){
$data = post::destroy($_id);
if($data) {
return redirect()->route('home');
}
else {
dd('error cannot delete this post');
}
}
}
Anybody any idea what i am missing?
Thanks in advance
You have to replace this line <form action = "{{Route ('post.form')}}" method="post"> with <form action = "{{Route ('post.save')}}" method="post">
You are using wrong route. Please change to Route ('post.save')
EDIT: I found that one myself, the PostControler didnt return a view if there was an $_id
Thanks for the help everyone!
Thanks for pointing that out, it did bring my from back to life :) However it breaks the update function :S.
When i now click on the edit button, the form does no longer get filled with the data for the post, and "save" creates a new post in stead of updating it.

How to remove unwanted values from arrayed input?

I just wanted to ask how can we avoid this kind of output from arrayed input. Every time I update it, these symbols ["\"[ keeps on multiplying. I'll show you the problem and the code below.
Thank you your future answers.
Route::resource('setups','SetupController');
public function index()
{
$data = DB::table('setups')->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
return view ('adminpanel.setup.index',['data' => $data,'socials' => $socials]);
}
index.blade.php
<form action="{{ route('setups.edit',$data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{$social}}" class="form-control" disabled>
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function edit($id)
{
$data = DB::table('setups')->first();
$setup = DB::table('setups')->where('id', $id)->first();
if (!empty($data)) {
$socials = explode(',',$data -> social);
}else{
$socials = [];
}
if($setup){
return view ('adminpanel.setup.edit',['data' => $data,'socials' => $socials]);
}else{
return redirect('setups');
}
}
.
edit.blade.php
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
<form>
.
public function update(Request $request, Setup $setup)
{
$data = Input::except('_token', 'submit', '_method');
$tbl = decrypt($data['tbl']);
unset ($data['tbl']);
$data['updated_at'] = date('Y-m-d H:i:s');
DB::table($tbl)->where(key($data), reset($data))->update($data);
session::flash('message','Setup updated successfully!!!');
return redirect()->route('setups.index');
}
Solved! I just added this code in my SetupController#update to illuminate those unwanted divider or separator(whatever) before
sending to database.
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}
laravel escaped data by default. It was not giving any error,whenever
you retrieve data from database to throw in your blade view.Database
data escaping is good practice.
As you showed your data,there is some unwanted data.Before you attempt to save your data,you may trim($yourString) to remove unwanted white-space from start & end of a string.
And You must not let blank or empty string to view in your blade. So, you might use blank($var) to check whether it is blank or not?
<form method="POST" action="{{ route('setups.update', $data->id) }}">
<div class="row">
<div class="col-md-12" id="socialGroup">
#foreach($socials as $social)
#if(!blank($social))
<div class="form-group socialField">
<label class="bmd-label-floating">Social Links</label>
<input type="text" name="social[]" value="{{ $social }}" class="form-control">
<i class="fa fa-plus"></i>
</div>
#endif
#endforeach
<div class="alert alert-danger" id="socialError">
<p><strong>Sorry! </strong>You've reached the max number for social links form.</p>
</div>
</div>
</div>
Solved! I just added this code in my SetupController#update
if (Input::has('social')) {
$data['social'] = implode(',',$data['social']);
}

how to redirect and show error validateion in laravel

good day,
I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist )
if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message.
how to prevent form resetting from inputs value?
here is my code
controller code
enter code here
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
{
$product=new productModel();
// start add
$product->name=$request->input('name');
$product->save();
$add=$product->id;
$poducten=new productEnModel();
$poducten->id_product=$add;
$poducten->name=$request->input('name');
$poducten->price=$request->input('price');
$poducten->save();
$dataview['message']='data addes';
}else{
$dataview['message']='name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my routes
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
I hope that I understood your question.
Instead of using {{ Request::old('price') }} use {{ old('price') }}
This should retrieve the form data after page was reloaded.
Try the below the code for error display in view page
$validator = Validator::make($params, $req_params);
if ($validator->fails()) {
$errors = $validator->errors()->toArray();
return Redirect::to($web_view_path)->with('errors', $errors);
}
You want to automatically redirect to another page submit the form using ajax and use below the settimeout menthod.
setTimeout(function(){ // Here mentioned the redirect query }, 3000);
//use $request instead of $_POST
if($request->isMethod('post'))
{
if(isset($request['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist

Laravel simple validation doens't work on resource method

Basically i have this form on userblog/create.blade.php
<form action="{{route('userblog.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label style="font-family: SansBold">تیتر وبلاگ:</label>
<input type="text" name="blog_title"
class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">
Save
<i class="icon-arrow-left13 position-right"></i></button>
</div>
<br/>
</form>
with this route on web.php
Route::group(['middleware' => ['auth:web'], 'prefix' => 'page'], function () {
$this->resource('userBlog', 'UserBlogController');
});
now I'm trying to check posted form on Controller with this code and store them on database:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'blog_title' => 'required|min:10',
'blog_content' => 'required|min:10',
]);
if ($validator->failed()) {
return back();
} else {
dd('store on database');
}
}
in this my code i get
Route [userblog.store] not defined
error and when i change form action to /page/userBlog i get [] on $validator
The routes name should be like resource name. Replace your resource name or Route name like:
$this->resource('userblog', 'UserBlogController');
or
.. action="{{route('userBlog.store')}}"
BTW, It's not a validation error. Just fix your route.

Edit page show blank in laravel

I have news details inserted and i need to show it on the edit page but when i try to edit and delete it shows blanks page insert and show is working properly. i have been stucked on this from morning. id is getting from the database but it shows a blank page,Not using any Form helper
1.what's problem,is it on route file
2.is it on Controller file
route.php
Route::get('/', function () {
return view('welcome');
});
Route::resource('books','BookController');
Route::resource('news','NewsController');
Auth::routes();
Route::get('/news','NewsController#index')->name('news');
//Route::get('/news/create','NewsController#create');
//Route::get('/news/edit','NewsController#edit');
Edit.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
NEW BEE NEWS DETAILS
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form method="post" action="{{route('news.update',[$news->id])}}"
enctype="multipart/form-data">
{{csrf_field()}}
<input type="hidden" name="_method" value="put">
<div class="form-group">
<label>NEWS TITLE</label>
<input type="text" name="atitle" id="atitle" class="form-control"
placeholder="PLEASE ADD TITLE OF NEWS" value="{{$news->name}}">
<p class="help-block">Example: SELFY PLAYSHARE </p>
</div>
<div class="form-group">
<label>NEWS</label>
<textarea name="news" id="news" class="form-control" {{$news->news}}></textarea>
<p class="help-block">DETAILED NEWS HERE</p>
</div>
<div class="form-group">
<label>NEWS LINK</label>
<input type="text" name="alink" id="alink" class="form-control"
placeholder="PLEASE ADD LINK OF NEWS" value="{{$news->alink}}">
<p class="help-block">Example: https://play.google.com/store/apps/selfyplusure</p>
</div>
<div class="form-group">
<label>NEWS IMAGE</label>
<input type="file" name="addimage" id="addimage" value="{{$news->imagename}}">
</div>
<button type="submit" class="btn btn-default">ADD NEWS</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
NewsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\News;
use Illuminate\Http\Request;
class NewsController extends Controller
{
public function index()
{
$news = News::all();
return view('news.index', ['news' => $news]);
}
public function create()
{
return view('news.create');
}
public function store(Request $request)
{
$news=new News();
if($request->hasFile('addimage')){
$request->file('addimage');
$imagename=$request->addimage->store('public\newsimage');
$news->name = $request->input('atitle');
$news->alink = $request->input('alink');
$news->news = $request->input('news');
$news->imagename = $imagename;
$news->save();
if($news) {
return $this->index();
} }
else{
return back()->withInput()->with('error', 'Error Creating News ');
}
}
public function show(News $news)
{
//
}
public function edit(News $news)
{
$news=News::findOrFail($news->id);
return view('news.edit',['News'=>$news]);
}
public function update(Request $request, $id)
{
$news = News::findOrFail($id);
// update status as 1
$news->status = '1';
$news->save();
if ($news) {
// insert datas as new records
$newss = new News();
//On left field name in DB and on right field name in Form/view
$newss->name = $request->input('atitle');
$newss->alink = $request->input('alink');
$newss->news = $request->input('news');
$newss->imagename = $request->input('addimage');
$newss->save();
if ($newss) {
return $this->index();
}
}
}
public function destroy($id)
{
$news = News::findOrFail($id);
$news->status = '-1';
$news->save();
if ($news) {
return $this->index();
}
else{
return $this->index();
}
}
}
Link to delete and Edit
<td><input type="button" name="edit" value="EDIT">
<td><input type="button" name="delete" value="DELETE"></td>
This is the link to edit
<td><input type="button" name="edit" value="EDIT">
For delete please go through
Delete
In your controller try to use this.
return view('news.edit',compact('news'));

Categories