So I'm new in laravel and I'm trying to create a rest api to return a specific item of my data database
http://127.0.0.1:8000/api/items/1010100203
And I'm getting []
So I have a array of json objects like
[{"No_":"1010100203","Price:"23","Description":"Item1"},{"No_":"1010100204","Price":"15","Description":"Item2"},{"No_":"1010100205","Price":"12","Description":"Item3"}]
in my database and I want to get my item with "No_" 1010100203.
In controller I have this function
public function find($id){
return Item::where('No_', 'like', $id)->get();
}
I've also tried to create a find function to only return $item and also returned []
I think I need to parse my array but I don't know how to do this..
And in my route api file,
Route::get('items/{id}', 'ItemController#find');
Also tried with Manager,
ItemController,
public function find($id){
$im= new ItemManager();
if (!empty($id))
$i=$im->GetItemIfExist($id);
return $i;
}
ItemManager
public function GetItemIfExist($id){
$result=\Illuminate\Support\Facades\DB::table('MR$Item')
->where('No_',$id)
->get();
return $result;
}
Why you use 'like'? Use '=' if you need exact match
Related
I've done a query at Laravel and to check result content, I've used dd, but, for some reason, when I remove the dd(), it throws an exception sayint "Undefined array key 0". However, with dd DO find the key.
Code is this:
public function getFormatosArticulo(Articulo $articulo){
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
dd($formatoRaw[0]);
$formato = $formatoRaw[0];
return $formato;
}
And dd output is this:
I guess you are calling getFormatosArticulo function for multiple times, and passed not exists id into it. The get() function will always return a empty collection even if no data matched.
Can you test your function use code below and check if id does exists or not?
public function getFormatosArticulo(Articulo $articulo){
try {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
$formato = $formatoRaw[0];
return $formato;
catch (Exception $e) {
dd($articulo->id); // i guess there is no articulo_id equal this in formato table.
}
}
The reason this happens is that dd stands for “dump and die” so your first iteration goes through but you don’t check the rest because you use die(). A solution to this can be as simple as:
public function getFormatosArticulo(Articulo $articulo) {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->get();
if ($formatoRaw) {
$formato = $formatoRaw[0];
return $formato;
}
}
Since you are only interested for the [0] position though a similar approach would be:
public function getFormatosArticulo(Articulo $articulo) {
$formatoRaw = Formato::where('articulo_id', '=', $articulo->id)->first();
if ($formatoRaw) {
return $formatoRaw;
}
}
Queue.php
class Queue extends Component
{
public function Data()
{
$fgd = FaddddxO::where('seus',$this->stas)
->whereNu('achieve_by');
if ($this->filter == '' && $this->stus != 'x Error')
{
$fax->where(function ($query) {
$query->whereDate('created_at', Carbon::today())
->orwhereDate('d_datetime', Carbon::today());
});
} else if ($this->filter == 'ries'){
$fassssxSss->where('resd_ag','>=',3)->whereNull('archive_by');
} else if ($this->filter == 'ponse'){
$favfhdjdfh->where(function ($query) {
$query->whereDate('created_at','<=' ,Carbon::now()->subDays(3))
->orwhereDate('dvkjdvvbfshnd_datetime','<=' ,Carbon::now()->subDays(3));
})->whereNull('archive_by');
}
}
In the Data() function, paginate with toArray() method is working. But when trying to populate links() in blade file it's showing the below error.
And this is the error:
Call to a member function links() on array
The error is quite explicit, and is caused by this
$this->faxStatus = $faxStatusData->orderByDesc('id')->paginate(5)->toArray();
A PHP array does not have any methods to call on it. You need stop at paginate() without any further casting if you want to keep the result paginated - by simply stopping with chaining more methods on after paginate() - like this
$this->faxStatus = $faxStatusData->orderByDesc('id')->paginate(5);
If you need to access the data of the paginated result, you can access that at $this->faxStatus->items(), without needing to cast it to an array.
If you - for whichever reason - need to convert it to an array, then you need to assign that to a different property, for example by doing
$this->faxStatus = $faxStatusData->orderByDesc('id')->paginate(5);
$this->faxStatusArray = $this->faxStatus->toArray();
And then accessing it as $this->faxStatusArray. I would however think that you can achieve the same by accessing $this->faxStatus->items().
I've written some code in Laravel to display only the images that are in mysql database, in Post table.
This is the function to display the images
public function index()
{
$posts = Post::all()->pluck('image');
return response()->json(['images' => $posts]);
}
And this is the response that i am getting which displays image filenames in JSON array
{
"images": [
"1509695371.jpg",
"1509696465.jpg",
"1509697249.jpg"
]
}
But i want to display them with the full URL, like this below in json format. It will be better using Laravel eloquent in that function but without using sql concatenation.
{
"images": [
"http://localhost:8000/images/1509695371.jpg",
"http://localhost:8000/images/1509696465.jpg",
"http://localhost:8000/images/1509697249.jpg"
]
}
Any help will be much more appreciated!
You can use map method on your collection:
public function index()
{
$posts = Post::all()->pluck('image')->map(function($image){
return "http://localhost:8000/images/".$image;
});
return response()->json(['images' => $posts]);
}
One solution is to make a AssetsService, it can have method for appending a path to an image: assetLink('images', $image).
An example implementation for this:
public function link(string $path, string $fileName): string
{
return sprintf(
'%s/%s/%s',
env('APP_URL'),
$path,
$fileName,
)
}
Now, you need to append to several paths. Simply make a seperate method that takes an array and iterates it using the method above. Another example:
public function linkArray(string $path, array $files): array
{
return array_map(function ($fileName) {
return $this->link($path, $fileName)
}, $files)
}
You can then call it like this: $assetsService->linkArray('images', $files). Remember you can use Dependency Injection to get a service instantiated by laravel's container.
This gives you a reusable set of methods for file paths without making your database do unnecessary work. Services are small classes that cost very little but give you a lot of transparency. You define what you use a service for or when something is at all a service.
This could be handled with a simple loop:
$posts = Post::all()->pluck('image');
foreach($posts AS $index => $image){
$posts[$index] = url("/images/".$image);
}
The url() helper returns a fully-qualified URL based on your config and the path passed, so
url("/images/1509695371.jpg")
should return
http://localhost:8000/images/1509695371.jpg
Edit: To include all Data, but still format images, you'll need to remove the ->pluck() function and loop $posts, then $post->images:
$posts = Post::all();
foreach($posts AS $post){
foreach($post->images AS $index => $image){
$posts->images[$index] = url("/images/".$image);
}
}
I have a method returning all job post data. This is what I have tried:
public function show($id)
{
$applicantData = Applicant::whereId($id)->first();
$jobData = Job::all();
//dd($jobData);
//dd($jobData->job_title);
return view('applicant.confirmation',compact("applicantData","jobData"));
}
dd($jobData); returns:
dd($jobData->job_title); it returns an error:
ErrorException in ApplicantController.php line 150: Undefined
property: Illuminate\Database\Eloquent\Collection::$job_title
How can I get the $jobData->job_title value?
You should iterate collections using the each method in Laravel:
$jobData->each(function ($item, $key) {
dd($item->job_title);
});
public function show($id)
{
$applicantData = Applicant::whereId($id)->first();
$jobData = Job::find($applicantData->job_id); //this will give you the job
dd($jobData);
dd($jobData->job_title);
return view('applicant.confirmation',compact("applicantData","jobData"));
}
You have to loop through $jobData since it will return all rows. Something like:
$jobData = Job::all();
foreach ($jobData as $job) {
echo $job->job_title;
}
They are object in arrays so you can directly pickout the value. If you need first item then $jobData[0]->job_title or $jobData->first()->job_title or you can loop foreach($jobData as $data){$data->job_title}
$jobData is a collection so you cannot directly access job_title like $jobData->job_title. I figure you want to access them in your view file. hence do following
#foreach($jobData as $job)
{{ $job->job_title }}
#endforeach
I have a function in controller to remove category and its image file. But i am not able to access the path property. I am getting this error Undefined property: Illuminate\Database\Eloquent\Collection::$path. It is returning path but i am unable to use it.
public function remove($id) {
//$category = Category::find($id)->delete();
$category_image = CategoryImage::where('category_id', '=', $id)->get(['path']);
echo $category_image->path;
//return back();
}
You can use first() if you need to get just one object:
$category_image = CategoryImage::where('category_id', '=', $id)->first();
if (!is_null($category_image)) { // Always check if object exists.
echo $category_image->path;
}
When you're using get(), you're getting a collection. In this case you can iterate over the collection and get data from each object, or just use index:
$category_image[0]->path;
You get a collection, you have to loop throug the collection this way:
foreach ($category_image as $image) {
echo $image->path;
}