How to decode in laravel join - php

I have json resource collection like this
<?php
namespace App\Http\Resources;
use App\Models\Curriculum;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;
class CurriculumDisplayResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title_section' => json_decode($this->title_section),
'learning_objective'=> json_decode($this->learning_objective),
'content_detail' =>
DB::table('curriculums')
->join('content_texts','curriculums.id','=','content_texts.curriculum_id')
->join('content_files','curriculums.id','=','content_files.curriculum_id')
->join('content_videos','curriculums.id','=','content_videos.curriculum_id')
->join('quizzes','curriculums.id','=','quizzes.curriculum_id')
->select('content_texts.title_text','content_texts.text_course',
'content_files.title_file','content_files.file_course','content_videos.title_video',
'content_videos.video_course','quizzes.title_quiz','quizzes.question','quizzes.answer','quizzes.right_answer')
->get(),
'parent_id' => $this->id,
];
}
}
Can I json decode the result of join quiz?, I just want to json decode the quizzes result. when I'm try display this json resource the result like this
this is the controller
<?php
namespace App\Http\Controllers\Course;
use App\Http\Controllers\Controller;
use App\Http\Resources\CurriculumResource;
use App\Models\Curriculum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CurriculumController extends Controller
{
public function index()
{
return Curriculum::all();
}
public function store (Request $request)
{
$c = new Curriculum();
$c->title_section = json_encode($request->get('title_section'));
$c->learning_objective = json_encode($request->get('learning_objective'));
$c->user_id = Auth::id();
$c->course_id = $request->get('course_id');
$c->save();
return response(new CurriculumResource($c));
}
}
What's wrong with my code?, I've also made cast for title_quiz, question, answer and right_answer.

Hope this help your problem. It seems like you have double quotation mark
On your Model which has title_quiz, question, answer, and right_answer, add this line of code (depend on your Model):
Model.php
public function getTitleQuizAttribute($value){
return str_replace('\"','', $value);
}
public function getQuestionAttribute($value){
return str_replace('\"','', $value);
}
public function getRightAnswerAttribute($value){
return str_replace('\"','', $value);
}
public function title_quiz($value){
return str_replace('\"','', $value);
}
public function getAnswerAttribute($value){
return json_decode($value);
}
They will modify your string first then pass it to your response
Docs

Related

Laravel Tables Join

I have three tables:
notes: id, business_id, note
businesses: id, title, description
businessimages : id, business_id, image
I get my customers notes with this:
$customer = Auth::guard('customer-api')->user();
$notes = Note::where('customer_id', $customer->id)->with('business:id')-
>orderBy('id', 'desc')->get();
Now I want to get notes.id, businesses.id, businesses.title, businesses.description, businessimages.image for each notes and show all of them in one json array
How could I do?
Note::where('customer_id',$customer->id)
->join('businesses', 'businesses.id', '=', 'notes.buisness_id')
->join('businessimages', 'businesses.id', '=', 'businessimages.buisness_id')
->select(notes.id, businesses.id, businesses.title, businesses.description,businessimages.image)
->get();
Note model;
public function business() {
return $this->hasOne('App\Business', 'business_id', 'id');
}
Business mode;
public function businessImage()
{
return $this->hasOne('App\BusinessImage', 'business_id', 'id');
}
Your controller;
$notes = Note::where('customer_id', $customer->id)->with('business.businessImage')->orderBy('id', 'desc')->get();
You should consider using API Resources
This is a great way to organize a model(or a collection of models as well).
App\Note
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
public function business()
{
return $this->belongsTo('App\Business');
}
}
App\Business
namespace App;
use Illuminate\Database\Eloquent\Model;
class Business extends Model
{
public function note()
{
return $this->hasOne('App\Note');
}
public function businessImage()
{
return $this->hasOne('App\BusinessImage');
}
}
App\BusinessImage
namespace App;
use Illuminate\Database\Eloquent\Model;
class BusinessImage extends Model
{
protected $table = 'businessimages';
public function business()
{
return $this->belongsTo('App\Business');
}
}
App\Http\Resources\Note
namespace App\Http\Resources;
class Note
{
public function toArray($request)
{
return [
'noteId' => $this->resource->id,
'businessId' => $this->resource->business->id,
'businessTitle' => $this->resource->business->title,
'businessDescription' => $this->resource->business->description,
'businessImage' => $this->resource->business->businessImage->image
];
}
}
Somewhere in a controller
use App\Http\Resources\Note as NoteResource;
public function foo()
{
$customer = Auth::guard('customer-api')->user();
$notes = Note::where('customer_id', $customer->id)->with(['business','business.businessImage'])->orderBy('id', 'desc')->get();
return NoteResource::collection($notes);
}

Create nested API

I'm trying to make an api that have lists and inside each list there is anther list inside of it called cards and the cards list is the cards of this list.
I tried to show it in index function and didn't work it was like this:
public function index()
{
// $list = List -> cards();
$list = List::cards();
return response( $list );
}
Card Model:
public function list()
{
return $this->belongsTo( List::class() );
}
Card Model:
public function cards()
{
return $this->hasMany( Card::class() );
}
What i want to output is json data like this:
"lists":[
'name':listname
'cards':[
'card one': card name,
]
]
If you use Laravel framework use Resource for response, in Resource of laravel you can load cards. For example in ListController :
public function index()
{
return ListResource::collection(List::all()->paginate());
}
And in ListResource :
public function toArray($request)
{
'cards' => CardResource::collection('cards');
}
belongsTo or hasMany accepts model name as a first argument. In your case you need to pass your model class name in your relations methods.
public function list()
{
return $this->belongsTo(List::class);
}
and
public function cards()
{
return $this->hasMany(Card::class);
}
So if you want to receive models including relations you can use with method.
return response(List::query()->with('cards'));
You can use resources.
Http\Resources\List:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class List extends JsonResource
{
public function toArray($request)
{
$cards = [];
foreach ($this->cards as $card) {
$cards[] = $card->name;
}
return [
'name' => $this->name,
'cards' => $cards,
];
}
}
Http\Controllers\ListController:
namespacce App\Http\Controllers;
use App\Http\Resources\List as ListResource;
use App\Components\List;
class ListController extends Controller
{
$lists = List::query()->get();
return ListResource::collection($lists)->response();
}

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

Class "MenuModel" not Found

I get this error when i try to run my Laravel
Class 'Menumodel' not found
in HasRelationships.php (line 487)
Here is my data structure
And this is MainComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;
use App\Menumodel as menu;
class MainComposer
{
public $items = [];
public function __construct()
{
$this->items = menu::tree();
}
public function compose(View $view)
{
$view->with('items', end($this->items));
}
}
MenuModel
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Menumodel extends Model
{
//
public $table = 'Menu';
protected $fillable = ['MenuParent','MenuName','MenuPath','MenuIcon','MenuOrder','RouteName'];
public function parent() {
return $this->hasOne('Menumodel', 'MenuCode', 'MenuParent');
}
public function children() {
return $this->hasMany('Menumodel', 'MenuParent', 'MenuCode');
}
public static function tree() {
return static::with(implode('.', array_fill(0, 4, 'children')))->where('MenuParent', '=', NULL)->get();
}
}
I aldredy try this use \App\Menumodel as menu; but still no different. How can i fix it ?
Your relationships are incorrect. You need to provide the full class namespace.
return $this->hasOne(Menumodel::class, '...', '...');
return $this->hasMany(Menumodel::class, '...', '...');
I've also removed your local and foreign keys because if using Laravel, these are typically snake_case, not StudlyCase, so you may need to double check those too.

Fetching only the soft deleted records

i have created a method to fetch only the soft deleted lessons in my LessonsController
i'm not getting what should be the route my lessoncontroller
<?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())
]);
}
//delete a lesson by id
public function destroy($id)
{
$dlesson = Lesson::find(input::get('id'));
if(! $dlesson) {
return $this->respondNotFound();
}
$dlesson->delete();
return $this->respondDeleted('Lesson deleted successfully');
}
public function deletedLessons()
{
$deleted_lessons = Lesson::onlyTrashed()->get();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
}
i have tried with a deleted record like
http://localhost:8000/api/v1/lessons/11
Thank You
Make sure:
You've used softDeletes() method in migration and executed this migration
You're using SoftDeletes trait in the model
You've added deleted_at to $dates property in the model
https://laravel.com/docs/5.3/eloquent#soft-deleting
After doing all that your query will work just fine and will return only soft deleted lessons:
$deleted_lessons = Lesson::onlyTrashed()->get();

Categories