Laravel Restful Api: Call to a member function toBase() on null - php

I'm using Laravel 5.8 and I wanted to retrieve some data from an Api route:
Route::prefix('v1')->namespace('Api\v1')->group(function(){
Route::get('/articles','ArticleController#index');;
});
Then I made a Resource Collection and a Controller as well:
ArticleCollection.php:
public function toArray($request)
{
return parent::toArray($request);
}
ArticleController:
public function index()
{
$articles = Article::all();
return new ArticleCollection($articles);
}
Now it properly shows data:
{"data":[{"art_id":3,"art_cat_id":15,"art_author_id":23973,"art_title":"\u0627\u062d\u06cc\u0627\u06cc...
But when I change the Resource Collection to this:
public function toArray($request)
{
return [
'title' => $this->art_title,
'desc' => $this->art_description,
];
}
And trying to find an specific article in the Controller:
public function index()
{
$articles = Article::find(1);
return new ArticleCollection($articles);
}
I will get this error somehow:
FatalThrowableError
Call to a member function toBase() on null
So what's going wrong here? How can I solve this issue?

Change this:
public function index()
{
$articles = Article::find(1);
return new ArticleCollection($articles);
}
to this:
public function index()
{
$articles = Article::where('id',1)->get();
return new ArticleCollection($articles);
}
This is because the find returns just one record and you are converting that to a collection, by using get() you can return a collection as you intend to here.

Related

Too few arguments to function Illuminate\Database\Eloquent\Builder

I have 2 model one is task and another is order. I have used here one to many relation. Here is my code
public function orders(){
return $this->hasMany(Order::where('service_id', null), 'offerid');
}
for task
public function task()
{
return $this->belongsTo(Task::class, 'id');
}
I have to fetch only those table who have service_id null. when i make like this then showing error Too few arguments to function Illuminate\Database\Eloquent\Builder.
$tasks = Task::where('sub_category', $id)->with('serimages', 'serSignleImg', 'user', 'orders')->get();
This is the query where i fetching all data. I have pass them through api
You have error in your relation method
public function orders(){
return $this->hasMany(Order::class, 'offerid')->whereNull('offerid');
}
or you can do like this
public function orders(){
return $this->hasMany(Order::class, 'offerid');
}
$tasks = Task::where(['sub_category', $id)->with('serimages', 'serSignleImg', 'user', 'orders'=>function($query){$query->whereNull('offerid')}])->get();

Laravel redirect()->action not working and show missing parameters

PHP Version:7.2
Laravel Version:6.2
I am doing a simple project by laravel by article.
When I meet with redirect()->action, I am a little confused about that.
I want to pass a variable named id by redirect()->action but it does't work.
Error Message is Missing required parameters for [Route: blog/post.show] [URI: blog/post/{post}].
If I remove the variable name, only pass the variable value and it would work. I read the manual but still could not understand the reason. Could you help me explain the logic. Thank you. Below is the sample code.
Router.php
Route::group(['prefix' => 'blog',
'as' => 'blog/',
'namespace' => 'Blog'],
function(){
Route::resource('/post',"PostController");
});
PostController.php
Create new blog post ( wrong )
Couldn't understant why this does't work ? Variable name($id) is the same.
public function store(Request $request)
{
$post = new BlogPost;
$post->title = $title;
$post->content = $content;
$post->save();
return redirect()->action(
'Blog\PostController#show', ['id' => $post->id]
);
}
Create new blog post ( correct )
public function store(Request $request)
{
$post = new BlogPost;
$post->title = $title;
$post->content = $content;
$post->save();
return redirect()->action(
'Blog\PostController#show', [$post->id]
);
//Or 'Blog\PostController#show', $post->id
}
Show the new blog post
public function show($id)
{
$post = BlogPost::find($id);
if(! $post) {
abort(404);
}
$content = $post->content;
return view("blog.post", [
"title" => $post->title,
"content" => $content,
]);
}
Thank you
Here is code :
return redirect()->route('routename', ['id' => 1]);
You got the error message because you are using the Resource Route and it will automatic bind the Model with Route
For More Info please refer: https://laravel.com/docs/6.x/routing#route-model-binding
I encountered this error myself when trying to use a redirect()->action. Here's a simple example that will fail in just the same way.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['id' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);
The reason this fails is because default stub used by Route::resource for show is the same as the resource name. Have a read here: https://laravel.com/docs/9.x/controllers#actions-handled-by-resource-controller
Solution 1
We could change our original example to using 'somethingsimpler' instead of 'id'.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['somethingsimpler' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);
However, this seems to negate the whole purpose of using redirect()->action.
Solution 2
Reading further in the same document linked above, it seems you can set the resource name https://laravel.com/docs/9.x/controllers#restful-naming-resource-route-parameters.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], ['id' => 7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController)->parameters([
'somethingsimpler' => 'id'
]);
Solution 3 - Recommended
Reading the rest of the document, it becomes obvious that you can probably get away with not even naming the parameter.
class SimpleController extends Controller {
public function index() {
return redirect()->action([static::class, 'show'], [7]);
}
public function show($id) {
// ... code goes here ...
}
}
And in the routes somewhere:
Route::resource('somethingsimpler', SimpleController);

Trying to get property 'title' of non-object (View: /opt/lampp/htdocs/commonroom/resources/views/home.blade.php

App\Classes
public function enroll()
{
return $this->hasMany(Enrolls::class,'cid');
}
App\Enrolls
public function classes()
{
return $this->belongsTo(Classes::class);
}
controller
public function index()
{
$enrolls = Enrolls::all();
return view('home')->with('enrolls', $enrolls);
}
blade
{{$enroll->classes->title}}
I was trying to get data from enrolls table. this contains two foreign Keys.
SCREENSHOT
You should try this:
public function index()
{
$enrolls = Enrolls::with('classes')->get();
return view('home',compact('enrolls'));
}

Laravel Dingo FindOrFail returns empty array

I have a table sites with list of sites with following columns ('id', 'path', 'site_link'). I've written in a Site model public $timestamps = false; so that it won't try to work with time what I don't need.
Also I have the following routes
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->get('sites', 'App\Http\Controllers\SiteController#index');
$api->get('sites/{site}', 'App\Http\Controllers\SiteController#show');
});
The first one is working fine and returning all the data, however the second one is returning just [].
I have a controller which is below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Site;
class SiteController extends Controller
{
public function index()
{
return Site::all();
}
public function show(Site $site)
{
return Site::findOrFail($site);
}
public function store(Request $request)
{
$site = Site::create($request->all());
return response()->json($site, 201);
}
public function update(Request $request, Site $site)
{
$site->update($request->all());
return response()->json($site, 200);
}
public function delete(Site $site)
{
$site->delete();
return response()->json(null, 204);
}
}
The show method in your SiteController is taking a Site object. However the route is set up to only take the siteId. The code below should work for you based on how you've set up your routes.
public function show($site)
{
return Site::findOrFail($site);
}
Apply same to all your other controller methods since you want pass the site id via the url to the controller methods.

How use find method to model

I have actionView($id) method in my controller. And have 2 models Posts and User and I want to get one posts(with user['name']). I have main gridview a when clicked for item have url like that:
http://localhost/test/basic/site/1
last 1 it's a this $id parameter.
Now my method is:
public function actionView($id)
{
if(Yii::$app->user->isGuest)
{
return $this->redirect(['login']);
}
else
{
$data = Posts::find($id)->joinWith('user');
return $this->render('detail',['data'=>$data]);
}
}
but I have error:
Setting unknown property: yii\widgets\DetailView::0
You have to define the relation in your Posts-Model like this:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
After that you can get the User with this:
Posts::find($id)->with('user')
You can find it in the documentation:
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relational-data

Categories