laravel 5.7 data not passed to the view - php

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

Related

How to decode in laravel join

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

How can I pass a parameter from the controller index function to the model's functions? LARAVEL

//------------------------------//
//below is the controller index function code //
//------------------------------//
public function index($from, $to,$id)
{
$data=Attendance::where('attendance_date','>=',$from)
->where('attendance_date','<=',$to)
->with('userAttendance')//--> **I need to pass the $id to this function in the model**
->with('admin')
->get()
//---------------------------------//
//below is the model code //
//----------------------------------//
class Attendance extends Model
{
protected $table = "attendances";
protected $fillable=[
'attendance_date',
'admin_id',
];
//---> **i need the $id passed to here**
public function userAttendance()
{
return $this->belongsToMany('App\User', 'user_attendances','attendance_id','user_id')
->withPivot(
'present_absent',
'excuse',
'attendance_key_amount',
'verified_date',
'comment',
);
}
}
just try this
Controller:
public function index()
{
$id = 50;
Product::getId(50);
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public static function getId($id){
dd($id);
}
}

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 on delete objects call model event - deleted

Im trying to call model event - deleted. When Im deleting a video, I also want delete all comments which are associated with video, that is working fine. But I have also feeds table and when Im deleting video I want also delete all comments and comments feeds. Now when Im deleting video, I delete - video, video comments, video feed, but I need delete also video comment feeds.
The question is how I can make it possible to delete also comments feeds when Im deleting video?
Check VideoController.php destroy function
Video.php - Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
class Video extends Model
{
protected $table = 'videos';
public $timestamps = false;
use Sluggable, RecordsFeed;
public static function boot()
{
parent::boot();
}
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function comments()
{
return $this->hasMany('App\VideoComment', 'videoid', 'id');
}
public function member()
{
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
VideoComments.php - Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VideoComment extends Model
{
protected $table = 'videos_comments';
public $timestamps = false;
protected $fillable = [
'text', 'userid', 'date'
];
use RecordsFeed;
public function videos() {
return $this->belongsTo('App\Video', 'id', 'videoid');
}
public function member() {
return $this->belongsTo('App\Member', 'userid', 'member_id');
}
}
RecordsFeed.php
<?php
namespace App;
use App\Libraries\Portal;
trait RecordsFeed
{
protected static function bootRecordsFeed() {
static::created(function($model) {
$model->recordFeed('created');
});
static::deleted(function($model) {
$model->deleteFeed('deleted');
});
}
public function feeds() {
return $this->morphMany( Feed::class, 'feedable' );
}
protected function recordFeed($event) {
$this->feeds()->create([
'user_id' => (new Portal)->getMemberID(),
'type' => $event.'_'.strtolower(class_basename($this))
]);
}
protected function deleteFeed($event) {
$this->feeds()->delete();
}
}
VideoController.php destroy function
public function destroy($id)
{
$video = Video::findOrFail($id);
$video->comments()->delete();
$video->delete();
Session::flash('success', 'Video deleted');
return redirect()->route('video.index');
}
Why do you not use on delete cascade at the creation of your table ?
In your migration, when you create your foreign key, just specify the on delete action like this :
$table->foreign('your_key')->references('id')->on('your_table')->onDelete('cascade');
It will automatically delete rows which are associated to the parent object.
You can find more details in Laravel documentation just here.
You don't have do anything code, you can set in database and set delete on cascade with relationshiop.

Decorate eloquent model attribute - Laravel 5

I have an eloquent model like this:
<?php
namespace News\Model;
class News extends Model
{
public $fillable = [
'title',
'desc'
];
public function getUpperTitle(){
return strtoupper($this->title);
}
}
and have controller like this:
use News;
class NewsController extends Controller
{
public function index()
{
return News::all();
}
}
Now I want to return all news with uppercase of title (title Decorated) without call getUpperTitle() and just use eloquent function.
Result that I want:
[
{
"title":"NEWS 1",
"desc":"News Description1"
},
{
"title":"NEWS 2",
"desc":"News Description2"
}
]
Use an accessor in your Model class:
public function getTitleAttribute($value)
{
return strtoupper($value);
}
https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor

Categories