I can't update the field in laravel 5 - laravel

It is OK in Get, Post, Delete in my laravel code.
But I can't update the field.
function update in BookController.php
$data = $this->request->all();
If show the dd($data), it is null.
What reason?
Help me please.
BookRequest.php Code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'coment' => 'required'
];
}
}
BookController.php Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
protected $request;
protected $book;
public function __construct(Request $request, Book $book) {
$this->request = $request;
$this->book = $book;
}
public function update(BookRequest $request, $id) {
$data = $this->request->all();
$book = $this->book->find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
return response()->json(['status' => Response::HTTP_OK]);
}
}

If i were you i would replace the Controller like below:
<?php
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
public function update(BookRequest $request, $id) {
$book = Book::find($id);
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
}
If you have set up Route:model binding then you can simplify Code more better. Below code only works if you have a Route::model setup in your route file web.php.
Check this docs for more details:
https://laravel.com/docs/5.6/routing#route-model-binding
public function update(BookRequest $request, Book $book) {
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}

Try this:-
$request->all();
instead of
$this->request->all()

I have solved.
My request: http://127.0.0.1:8000/api/book
POST , key: _method: PUT
Update Code
$data = $request->all();
$book = Boook::find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
Regards.

Related

Target class [App\Sys\Http\Controllers\Api\LocationController] does not exist

I have setup Laravel 6 project but for some reason when php artisan route:list returns “Target class [App\Sys\Http\Controllers\Api\LocationController] does not exist." I'm new in Laravel and I can't understand why the controller doesn't work. Can anyone please help me?
Here are my code:
LocationController.php
<?php
namespace App\Http\Controllers\Api;
//use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Location;
class LocationController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['locations' => Location::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$location= Location::create([
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description
]);
return response()->json(['location'=>$location],200);
}
public function show($id)
{
$locations = Location::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['locations' => $locations],200);
}
public function update(Request $request, $id)
{
$location = Location::find($id);
$location->code = $request->code;
$location->name = $request->name;
$location->description = $request->description;
$location->save();
return response()->json(['location'=>$location], 200);
}
public function destroy($id)
{
$location = Location::where('id', $id)->delete();
return response()->json(['location'=>$location],200);
}
public function deleteAll(Request $request){
Location::whereIn('id', $request->locations)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
My route file:
api.php
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::namespace('App\Sys\Http\Controllers')->group(function () {
Route::get('/menuslevel0',['uses' => 'MenuController#menus_level_0']);
Route::resource('locations','Api\LocationController');
});
You controller is in the App\Http\Controllers\Api, not in the App\Sys\Http\Controllers namespace. Remove the locations resource route in the namespace App\Sys\Http\Controllers group and create a new one.
Do this
...
Route::namespace('App\Sys\Http\Controllers')->group(function () {
Route::get('/menuslevel0',['uses' => 'MenuController#menus_level_0']);
});
Route::namespace('App\Http\Controllers')->group(function () {
Route::resource('locations','Api\LocationController');
});
...
Your controller is in App\Http\Controllers\Api and your route is pointing to App\Sys\Http\Controllers\Api.
You must change:
Route::namespace('App\Sys\Http\Controllers')->group(function () {
// Your routes
});
To:
Route::namespace('App\Http\Controllers')->group(function () {
// Your routes
});

Larave 6 l “Creating default object from empty value”

Here, I have setuo CRUD table with laravel, vuetify and vue . I could successfull create and read data from the database. But, for some reason my update and delete are not working. I am getting error like:
{message: "Creating default object from empty value", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php"
line: 53
message: "Creating default object from empty value"
trace: [{file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php", line: 53,…},…]
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$stage= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description,
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code; //line 53
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=> $stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
I just found they you are using uuid as id not increment. that why you get error like that:
to solve your problem you need to add the field to your model;
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
}
I hope this time you can solve your problem. happy coding.
Edit you can read docs for more info

How do I see published posts count with Eloquent using a ServiceProvider

I have a Blog Categories in the sidebar.blade.php
#foreach ($categories as $category)
<li>
<i class="fa fa-angle- right"></i> {{$category->title}}
<span class="badge pull-right">{{$category->posts()->count()}}</span>
</li>
#endforeach
But this count give me all the posts in my database, even the ones that are scheduled to post at a later date.
PostsController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Category;
class PostsController extends Controller
{
protected $limit = 3;
public function index()
{
$posts = Post::with('author')
->latestFirst()
->published()
->paginate($this->limit);
return view('posts.index', compact('posts'));
}
public function category(Category $category)
{
$categoryName = $category->title;
$posts = $category->posts()
->with('author')
->latestFirst()
->published()
->paginate($this->limit);
return view('posts.index', compact('posts', 'categoryName'));
}
Here's the Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use GrahamCampbell\Markdown\Facades\Markdown;
class Post extends Model
{
//Table Name
protected $table = 'posts';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
/*protected $fillable = [
'title',
'excerpt',
'body',
'categery_id',
'image',
];*/
protected $dates = ['published_at'];
public function author()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function getImageUrlAttribute($value)
{
$imageUrl = "";
if( ! is_null($this->image))
{
$imagePath = public_path() . "/img/" . $this->image;
if(file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}
return $imageUrl;
}
public function getDateAttribute()
{
return is_null($this->published_at) ? '' : $this->published_at->diffForHumans();
}
public function getExcerptHtmlAttribute(){
return $this->excerpt ? Markdown::convertToHtml(e($this->excerpt)) : NULL;
}
public function getBodyHtmlAttribute()
{
return $this->body ? Markdown::convertToHtml(e($this->body)) : NULL;
}
public function scopeLatestFirst($query)
{
return $query->orderBy('published_at', 'desc');
}
public function scopePublished($query)
{
return $query->where('published_at', '<=', Carbon::now());
}
}
Here's my Category.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
/*protected $fillable = [
'title',
'excerpt',
'body',
'categery_id',
'image',
'slug'
];*/
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
Web.php
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/category/{category}', [
'uses' => 'PostsController#category',
'as' => 'category'
]);
Route::resource('books', 'BooksController');
Route::resource('posts', 'PostsController');
Route::resource('categories', 'CategoriesController', ['except'=> ['create']]);
ComposerServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Category;
use App\Post;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('layouts.sidebar', function($view){
$categories = Category::with(['posts' => function($query){
$query->published();
}])->orderBy('title', 'asc')->get();
return $view->with('categories', $categories);
});
}
}
To recap on what I need done...
I want to just have my published post to be accounted for in the counter to show, not all the of the posts in my database..
(<span class="badge pull-right">{{$category->posts->count()}}</span>)
Post.php
public function scopePublished($query)
{
return $query->where('published_at', '<=', Carbon::now());
}
But this is not working right for me, does anyone know why?
Try this one:
<span class="badge pull-right">{{$category->posts()->published()->count()}}</span>
Didn't try but this should do the trick.

InvalidArgumentException route notdefined

I have error like (1/1) InvalidArgumentException
Route [home] not defined. whenever i used the store function but i'm pretty sure that i use the redirect method right what could be the possible error, all i wanted was to redirect to home once the store method is done.
web.php
<?php
Route::get('/', function () {
return view('main');
});
Route::get('/create', 'BuildingController#createBuilding');
Route::post('/store', 'BuildingController#store');
Route::post('home', 'BuildingController#getAllBuilding');
Building.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
public $timestamps = false;
protected $fillable = [
'id',
'building_name',
'building_information',
'building_image'
];
}
BuildingController.php
<?php
namespace App\Http\Controllers;
use App\Building;
use Image;
use Illuminate\Http\Request;
use App\Repositories\Building\BuildingRepository;
class BuildingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
private $building;
public function __construct(BuildingRepository $building)
{
$this->building = $building;
}
public function createBuilding()
{
return view('building.create');
}
public function store(Request $request)
{
$this->validate($request, array(
'building_name'=>'required',
'building_information'=>'required',
'building_image' => 'required'
));
$image = $request->file('building_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' .$filename);
Image::make($image)->resize(800,400)->save($location);
$buildings = array('building_name' => $request->building_name,
'building_information' => $request->building_information,
'building_image' => $filename);
$this->building->create($buildings);
return redirect()->route('home');
}
public function getAllBuilding()
{
$buildings = $this->building->getAll();
return view('building.home')->with('buildings', $buildings);
}
public function getSpecificRecord()
{
$buildings = $this->building->getById(1);
return view('building.show')->with('buildings', $buildings);
}
}
EloquentBuilding.php
<?php
namespace App\Repositories\Building;
use \App\Building;
class EloquentBuilding implements BuildingRepository
{
private $model;
public function __construct(Building $model)
{
$this->model = $model;
}
public function getById($id)
{
return $this->model->findOrFail($id);
}
public function getAll()
{
return $this->model->all();
}
public function create(array $attributes)
{
return $this->model->create($attributes);
}
public function update($id, array $attributes)
{
}
public function delete($id)
{
}
}
BuildingRepository.php
<?php
namespace App\Repositories\Building;
interface BuildingRepository
{
public function getById($id);
public function getAll();
public function create(array $attributes);
public function update($id, array $attributes);
public function delete($id);
}
Since you're using route(), you need to name the route. Also, make it get:
Route::get('home', 'BuildingController#getAllBuilding')->name('home');
Or:
Route::get('home', ['as' => 'home', 'uses' => 'BuildingController#getAllBuilding']);
You are trying to use route with post, replace it with get and also add/specify name attribute to call route using name.
Route::get('home', 'BuildingController#getAllBuilding')->name('home');
OR
Route::get('home', ['as' => 'home', 'uses' => 'BuildingController#getAllBuilding']);
Above both are comes with same output...

Undefined property: Illuminate\Validation\Validator::$errors in laravel

Undefined property: Illuminate\Validation\Validator::$errors in laravel
here is my controller file how to solve it i think here problem is any namespace where is it i do not know please guide me
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Route;
use Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\models\Designation;
use Validator;
use Illuminate\Support\Facades\Response;
class Cdesigination extends Controller
{
public $flight;
public function __construct(){
$this->flight = new Designation;
}
public function index()
{
return view('designation');
}
public function techer(Request $request) {
$Validator =Validator::make(array(
'name'=>Input::get('name'),
'detail'=>Input::get('detail')
),array(
'name' => 'required',
'detail' => 'required'
));
if ($Validator->fails()) {
return Response::json([
'success'=>false,
'error' =>$Validator->errors->toArray()
]);
}
else{
$this->flight->name = $request->name;
$this->flight->detail = $request->detail;
$this->flight->save();
return Response::json([
'success'=>true]);
}
}
$Validator->errors()->toArray()
Errors() is function, so the braces are important

Resources