Laravel form validator error - php

I want to validate the input fields before storing the data in database so i went through the laravel docs and followed these
php artisan make:request StoreLessons
in StoreLessons
public function rules()
{
return [
'title' => 'required|unique:lesson',
'body' => 'required',
];
}
in my controller
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\StoreLessons;
class LessonsController extends ApiController
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//add a new lesson to lessons table
public function store(StoreLessons $request)
{
Lesson::create($request->all());
//Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
}
now i'm getting this error
QueryException in Connection.php line 770:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_api.lesson' doesn't exist (SQL: select count(*) as aggregate from `lesson` where `title` = the)
i don't know why it's looking for lesson table i have a lessons table
but the store() function works with default validation
//this works fine but i wan to do the validation
public function store()
{
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
Thank You

unique:table,column,except,idColumn
The unique syntax goes as above and the first parameter passed is the table name.
public function rules() {
return [ 'title' => 'required|unique:lesson', 'body' => 'required', ];
}
The unique rule here looks for a table lesson. Try changing that to lessons

Please write below line after related model class name like this.
class xyz extends Model
{
protected $table = 'lessons';
code---
}
Try this.

Related

Base table or view not found: 1146 Table 'admin.model' doesn't exist

How to fix this error. I am trying to update data in table.
This is my controller
public function update($id)
{
$input = request()->all();
return response()->json(['success' => true], 200);
}
This is my model
namespace App\Models\Models;
use Illuminate\Database\Eloquent\Model;
class ModelsCategory extends Model
{
protected $table = 'models_categories';
protected $guarded = ['id'];
}
You have not made any updates within the function
Make changes like me
public function update(Requeat $request, $id)
{
ModelsCategory::where("id",$id)->update([
// Herer set your column and data like this
'tiltle'=>$request->title,
]);
return response()->json(['success' => true], 200);
}
Or you can use this.
first change route like this:
Route::post("/category/{modelscategory}","categorycontroller#update")
update mthod
public function update(Requeat $request, ModelsCategory $modelscategory)
{
$modelscategory->title=$request->title;
$modelscategory->save();
return response()->json(['success' => true], 200);
}
I hope I helped

laravel 5.7 data not passed to the view

I'm trying to pass my article data to the single page article named article.blade.php although all the data are recorded into the database but when I tried to return them in my view, nothing showed and the [ ] was empty. Nothing returned.
this is my articleController.php
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function single(Article $article)
{
return $article;
}
}
this is my model:
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use Sluggable;
protected $guarded = [];
protected $casts = [
'images' => 'array'
];
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function path()
{
return "/articles/$this->slug";
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
and this is my Route
Route::get('/articles/{articleSlug}' , 'ArticleController#single');
Change your code to
class ArticleController extends Controller
{
public function single(Article $article)
{
return view('article', compact('article'));
}
}
change route to
Route::get('/articles/{article}' , 'ArticleController#single');
And model
public function getRouteKeyName()
{
return 'slug';
}
See docs https://laravel.com/docs/5.7/routing#route-model-binding
You might not be getting any data because you have not specified that you're using title_slug as the route key for model binding in your model.
Add this to your model class and it should give you the data
public function getRouteKeyName()
{
return 'slug';
}
Then you can return the data in json, view or other format.
Depending on what you try to archive, you need to either ...
return $article->toJson(); // or ->toArray();
.. for json response or ..
return view(..., ['article' => $article])
for passing a the article to a certain view

laravel Column not found: 1054 Unknown column 'created_at' in 'order clause'

I have defined to not use timestamps, but still laravel forces to use timestaps... Im using laravel 5.6.
When I visit page for example - http://mypage/api/videos/21/comments
I get an error - "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'created_at' in 'order clause' (SQL: select * from videos_comments where videos_comments.video_id = ▶"
app/Providers/VideoComment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VideoComment extends Model
{
protected $table = 'videos_comments';
public $timestamps = false;
protected $fillable = [
'text', 'userid', 'date'
];
public function videos() {
return $this->belongsTo('App\Video', 'id', 'video_id');
}
public function member() {
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
app/Providers/Video.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Video extends Model
{
protected $table = 'videos';
public $timestamps = false;
use Sluggable;
public function sluggable() {
return [
'slug' => [
'source' => 'title'
]
];
}
public function comments() {
return $this->hasMany('App\VideoComment', 'video_id', 'id');
}
public function member() {
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
VideoCommentController.php function
public function index(Video $video) {
return response()->json($video->comments()->with('member')->latest()->get());
}
If you use latest() in your query then you have to add created_at in your db table, read more.
The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the created_at column.
You can easily use orderBy and first() instead of latest() when you haven't created_at column.

Laravel - Eloquent attach() not working for models

TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}

Laravel Api update and delete function

I'm building an API, i'm getting the following error while updating and deleting from table i'm using postman to test my api
//update error
QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: update `lessons` set `title` = , `body` = , `completed` = , `updated_at` = 2017-01-03 09:14:10 where `id` = 11)
//delete error
FatalErrorException in LessonsController.php line 80:
Call to a member function delete() on null
My controller LessonsController
<?php
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
class LessonsController extends ApiController {
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer) {
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index() {
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//fetch by id
public function show($id) {
$lesson = Lesson::find($id);
if(! $lesson) {
return $this->respondNotFound();
}
return $this->respond([
'data' => $this->lessonTransformer->transform($lesson)
]);
}
public function store() {
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated();
}
public function update(Request $request, $id) {
$ulesson = Lesson::find($id);
$ulesson->title = $request->input('title');
$ulesson->body = $request->input('body');
$ulesson->completed = $request->input('completed');
$ulesson->save();
return "Sucess updating user #" . $ulesson->id;
}
public function destroy(Request $request) {
$dlesson = Lesson::find($request->input('id'));
$dlesson->delete();
return "Employee record successfully deleted #" . $request->input('id');
}
}
my model Lesson
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
protected $fillable = ['title', 'body', 'completed',];
//protected $hidden =['title'];
}
the store and other functions are working fine
Thank You
In update
can you dd($request->input('title')) in line 69
I think you don't sent the value of title
and in delete
I think you have no value in id field
Please check you postman and set it like this
i just downloaded Insomnia and tested every thing is working fine as expected
i don't know why it's not working in postman though
Laravel APi Update Function...
According to this query no need to define keys
Controller Function
`
public function update(Request $request){
$reqdata = $request->all();
$reqdata['date_created'] = date('Y-m-d');
$lesson= Lesson::where('id',$request->id)->update($reqdata);
if ($lesson) {
return 'true';
}else{
return 'false';
}
} `
Your data type as attached image

Categories