laravel : Error Call to a member function all() on array - php

This is used to export excel
My controllers:
public function reportExport(Request $request)
{
return Excel::download(new ReportExport($request), 'LAPORAN ABSENSI.xlsx');
}
Export folder : ReportExport
return [
"att_cross" => $att_cross,
"belum_absen" => $belum_absen,
"absen" => $absen,
];
but, when I return one of the data is successful, for example :
return $absen;
I want to display the contents of the variable $absent, $belum_absen, $att_cross but I get an error message "Call to a member function all() on array "
how can I display the data for these three parameters?

Read the docs for Excel package, you need to map() the output.

Related

PHP - Is It possible to return 2 new Class Object

is there any possible to return a function in a multiple add new Class Object ?
THanks in advance.
example :
public function model()
{
return new Users(['...' => user1, .....]);
return new Customers(['...' => customer1, .....]);
}
You can put them in an array and return both. You can then access the object you want and process it further.
Once the function reaches the return statement lines/codes below, that won't get executed. If you use an Advanced IDE (PhpStorm which I use) it will show you a message saying "Unreachable...".
To archive your goal, you can pass them in an array.
public function model()
{
return [
'user' => new User(....),
'customer' => new Customers(...)
];
}

Shows only 3 most recent data

So I want to display the three most recent data from the 'berita' table.
i have created a function in controller, and an error appears Call to undefined method stdClass::take()
public function index()
{
$data = [
'berita' => $this->BeritaModel->allData()->last()->take(3)->get(),
];
return view('user.v_home_smk', $data);
}

No meta value from collection object

class SongsCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => SongResource::collection($this->collection),
'meta' => ['song_count' => $this->collection->count()],
];
}
}
in the controller
$data = new SongsCollection(Song::all());
dd($data);
`
it only display the image below, but without the meta array contain the song_count?
How to get the meta->song_count value ?
Laravel doc says:
Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when the resource is returned as a response from a route or controller method.
So, dd($data) will just dump the resource object which has the toArray method. If you want to get the meta field, you must call $data->toJson() method. If you just return $data in your api endpoint, laravel itself will call toJson method internally as stated in the above doc.
In the blade template, the laravel gives a song collection, which can not be retrive the meta from this collection, Below is how I get the meta data:
$datas = json_encode($datas,true);
//dd($data);
$datas = json_decode($datas);
// dd($datas);
foreach($datas->meta as $link){
echo $link;
}
Hope this helps.

404 page not working for some routes in laravel 5.4

I have a route like this:
web.php
Route::get('post/{slug}', [
'as' => 'post.single',
'uses' => 'PageController#getSingle',
]);
PageController.php
public function getSingle($slug)
{
//some db stuff and returning an array to view
return view('single', array('var1' => $var, 'var2' => $var2));
}
A post has a slug which is stored in the database.
If a post exists with slug, example: first-post
Then the route mysite.com/post/first-post works as expected.
But if a post doesn't exists, example: second-post
Then the route mysite.com/post/second-post gives me an error:
**ErrorException**
Trying to get property of non-object
I want it to show a 404 error page (404 page is already configured)
mysite.com/hellohello gives and 404 page, so it's working as expected.
Any suggestion what should I do?
Eloquent has a neat firstOrFail method which either returns the first entity it finds, or if there is none throws an ModelNotFoundException which laravel converts to a 404 page.
public function getSingle($slug)
{
$var = YourModel::where('slug', $slug)->firstOrFail();
return view('single', compact('var'));
}
I think you should update your function like:
And you can not close bracket in return view
public function getSingle($slug)
{
//some db stuff and returning an array to view
return view('single', array('var' => $var));
}
UPDATE after OP change the question content:
public function getSingle($slug)
{
//some db stuff and returning an array to view
$var = SOMEDBRESULT1;
$var2 = SOMEDBRESULT2;
return view('single', array('var1' => $var, 'var2' => $var2));
}
You can learn about how to get first record from db with laravel 5.4.

Laravel presenters for JSON responses

I’ve recently discovered that presenters (like this one) implement the decorator pattern and are a great way to add fields and logic to existing Laravel models. Take the following example for my question below:
// Tack on a new readable timestamp field.
public function timeago()
{
return $this->object->created_at->whenForHumans();
}
// Wrap an existing field with some formatting logic
public function created_at()
{
return $this->object->created_at->format('Y-m-d');
}
I can then use these presenter fields in my view:
{{ $object->timeago }}
{{ $object->created_at }}
How would you implement the decorator pattern for an API that returns JSON responses rather than Blade views? In all the Laravel/JSON articles I have read, objects are immediately returned without undergoing any transformation / presenter logic. e.g.:
// converting a model to JSON
return User::find($id)->toJson();
// returning a model directly will be converted to JSON
return User::all();
// return associated models
return User::find($id)->load('comments')->get();
How can I implement presenter fields in my JSON response?
$object->timeago
$object->created_at
As you mentioned, User::all returns JSON, so do something like:
Some function to get data and return a decorated response:
public function index()
{
$news = News::all();
return $this->respond([
'data' => $this->newsTransformer->transformCollection($news->toArray())
]
);
}
The above function will call Transformer::transformCollection:
<?php namespace Blah\Transformers;
abstract class Transformer {
public function transformCollection(array $items)
{
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
which in turn will call NewsTransformer::transform():
public function transform($news)
{
return [
'title' => $news['title'],
'body' => $news['body'],
'active' => (boolean) $news['some_bool'],
'timeago' => // Human readable
'created_at' => // Y-m-d
];
}
The end result being JSON with the format you require, in this case:
{
data: {
title: "Some title",
body: "Some body...",
active: true,
timeago: "On Saturday, 1st of March",
created_at: "2014-03-01"
}
}
By the way, Laracasts has an excellent series on building APIs -- hope that helps!
For clarity, the respond function in the first code snippet just wraps the data with a status code, and any headers, something like:
return Response::json($data, 200);

Categories