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();
Related
I want to create a laravel crud repository for a model. The model has 1 1:n and 1 n:n relationship.
class Product extends Model
{
protected $table = 'products';
protected $fillable = [
'description', 'merchantId', 'name', 'link', 'pictureUrl', 'ean', 'brand', 'aktPrice', 'affiliatePortal', 'programId'
];
public function prices() {
return $this->hasMany(Price::class);
}
public function categories() {
return $this->hasMany(Categorie::class);
}
}
Now I want to create a repository which has a save method and a controller for a restapi, which calls the save methode. My question is how should a save method looks that the entity is saved correctly and which mapping operations have to be done before that it works. I hope someone can help me and send me a save method, or a crud repository for my case and can help me to design the controller.
A Controller, with all the crud operations, look like this:
<?php
namespace App\Http\Controllers;
use App\Models\Room;
use Illuminate\Http\Request;
class RoomController extends Controller
{
public function index()
{
$rooms = Room::all()->toArray();
return $rooms;
}
public function add(Request $request)
{
$room = new Room;
$room->create($request->all());
return response()->json('The room successfully added');
}
public function getById($id)
{
$room = Room::find($id);
return response()->json($room);
}
public function update($id, Request $request)
{
$room = Room::find($id);
$room->update($request->all());
return response()->json('The room successfully updated');
}
public function delete($id)
{
$room = Room::find($id);
$room->delete();
return response()->json('The room successfully deleted');
}
}
I'm trying to fetch the created_at attribute in the model so I can put it in my relationship.
E.g. rows in exit_accession_goods created today should look at rows in entry_accession_goods that were made today or before it.
Here's what I've tried:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ExitAccessionGood extends Model
{
protected $fillable = ['exit_accession_id', 'norm_id', 'quantity'];
public function entry_goods()
{
return $this->hasMany('App\EntryAccessionGood', 'norm_id', 'norm_id')
->whereDate('created_at', '<=', $this->created);
}
public function packagings()
{
return $this->hasMany('App\PackagingItem', 'norm_id', 'norm_id');
}
public function getCreatedAttribute()
{
return "{$this->created_at}";
}
}
The $this->created returns an empty string.
Try this
public function getCreatedAttribute(){
return $this->attributes['created_at'];
}
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);
}
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
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.