Hiding pivot attribute - laravel

I know you can hide an entire pivot table as such
protected $hidden = ['pivot'];
How do you hide a specific field within pivot table, like
protected $hidden = ['pivot.created_at'];
The above does not work from what I've tested

After so much trying and looking into source of Laravel Model, i finally got it achieved.
Please put following method at your Model.
/**
* Convert the model instance to an array.
*
* #return array
*/
public function toArray()
{
$attributes = $this->attributesToArray();
$attributes = array_merge($attributes, $this->relationsToArray());
unset($attributes['pivot']['created_at']);
return $attributes;
}
This solves the purpose.

Related

getting error when applied WHERE clause on a model(parent) and then gets its related model(child) data in eloquent

I have a User model which is a parent and Project model which is a child. I created a one-to-many relationship between these two like below.
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function projects(){
return $this->hasMany('App\Project', 'user_id');
}
}
Project Model:
class Project extends Model
{
// Table Name
protected $table = 'projects';
//Primary Key
protected $primaryKey = 'project_id';
// Timestamps
public $timestamps = true;
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
when applying where clause on user model and then getting its related projects:
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::where('email', $request->input('client'))->projects;
}
}
getting error
Exception
Property [projects] does not exist on the Eloquent builder instance.
but when doing
$client = User::find(id)->projects;
above query is giving me results.
Result Expected: i want to get the User model data by WHERE() clause instead of Find() clause and then gets its related projects.
As the Error Says that you dont have property in the Builder
$client = User::where('email', $request->input('client'))->projects;
try this
$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;
here we are getting the user with the specific email and loading the realtion and here you get the relation as object
The source of your issue is that you have not yet retrieved any users. Before calling first() or get() on the query builder, you are limited to functions of the query builder.
Short version: call first() before accessing the projects
$client = User::query()
->where('email', $request->input('client'))
->first()
->projects;
Optional: add with('projects') to eager load the projects. This doesn't add any performance bonus in your case though, as you are only loading a single model.
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::with('projects')->where('id');
}
}
In HomeController this line will retrun collection of array.... In simple words it will return multiple records....
$client = User::where('email', $request->input('client'))->projects;
As you want single record use first (). To retrive single record... It will retrun first matching record...
$client = User::where('email', $request->input('client'))->first()->projects;

Delete on Eloquent doesn't delete Laravel 5.4

I am trying to make a delete functionality for pictures which users can upload. The model of the picture class:
class Picture extends Model
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
* #var array
*/
protected $fillable = ['original_file', 'resized_file'];
/**
* The attributes that should be mutated to dates.
* #var array
*/
protected $dates = ['deleted_at'];
/**
* Get the category that owns the question.
*/
public function user()
{
return $this->belongsTo(User::class);
}
Migration:
$table->timestamps();
$table->softDeletes();
The delete function which I have:
public function destroyProgress(Picture $progress){
$progress->delete();
dd($progress);
return view('client.home.profile', ['user' => Auth::user()]);
}
This code is executed and stoped at the dd($progress);. I would expect that this would return null because the $progress has been deleted. But this still returns an instance! Could someone please explain to me what I am doing wrong because I am lost for words.
Hard to explain, the object $progress created by dependency injection is not actually a model instance. Therefore, the delete event will not be fired.
You should use delete method on a model instance:
$picture = App\Picture::find(1);
$picture->delete();

how to update data into table using in laravel

I want to update data into table if the record exits if not then create a new record.
if(!empty($request->meta_title)){
$meta = new \stdclass();
$meta = VendorMeta::firstOrNew(['vendor_id' => $id]);
$meta->meta_title = $data['meta_title'];
$meta->meta_desc = $data['meta_desc'];
$meta->meta_keyword = $data['meta_keyword'];
$meta->save();
}
But I am getting this error:
MassAssignmentException in Model.php line 445:vendor_id
You should define which model attributes you want to make mass assignable, so in your VendorMeta class add following code:
protected $fillable = ['vendor_id'];
You need to set the $fillable property on your model.
Take a look at the docs under Mass Assignment.
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['meta_title', 'meta_desc', 'meta_keyword'];

Call to a member function on a non-object eloquent attach

I am having an issue with laravel not seeing my tags() method for attaching new tags on a new entry. I keep getting Call to a member function on a non-object when I try to run the method and attach tags to my Tile model. All methods are returning their relations. I followed the same order as the documentation says eloquent.
Controller
$tile = \Tiles\Tile::find($tile_id);
$tile->tags()->attach($tag_array);
Model
<?php namespace Tiles;
use Illuminate\Database\Eloquent\Model;
class Tile extends Model {
/**
* The Tile table
* #var string
*/
protected $table = 'tiles';
/**
* Pivot table for tags
* #var string
*/
protected $pivot = 'tag_tile';
/**
* Get the tags associated with the given tile
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tile_id', 'tag_id')->withTimestamps();
}
}
Try it
Model
public function tags() {
return $this->belongsToMany('Tiles\Tag', $this->pivot, 'tag_id', 'tile_id')->withTimestamps();
}
Thanks for all your help. I figured out the solution. I created a method in my model and pushed each to an array and fed it to the attach method. It works now.

Eloquent ORM all() not returning anything

Shoot me down if I this is a silly question, but I am really struggling to get this all() function working for me. It is returning empty list for me. Any help will be highly appreciated. I have got 2 rows in the newsletters table
Model looks like this -
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Newsletters extends Eloquent {
//use UserTrait, RemindableTrait;
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'newsletters';
/**
* The attributes excluded from the model's JSON form.
*
* #var array */
protected $guarded = array('newsletterId');
protected $fillable = array('name', 'subject','from_email','from_name');
public static $rules = array(
'name' => 'required|min:5',
'subject' => 'required|min:5',
'from_email' => 'required|email',
'from_name' => 'required'
);
}
My call in the controller is like this -
<?php
class newslettersController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//$newsletters = Newsletters::paginate(3);
$newsletters = Newsletters::all();
echo $newsletters;exit();
return View::make('newsletters.index', compact('newsletters'));
}
Any value - even 0000-00-00 00:00:00 - in the deleted_at column tells Laravel that the item has been deleted. Change your default value for that column to NULL or new items will be flagged as deleted on creation.
The $table->softDeletes() Schema function does this automatically if you use it in a migration.
As soon as you use the SoftDeletingTrait a global scope will be applied to every query with your model so all records where deleted_at is not NULL will be ignored.
Illuminate\Database\Eloquent\SoftDeletingScope:
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->whereNull($model->getQualifiedDeletedAtColumn()); // <<-- this
$this->extend($builder);
}
Change the default of your deleted_at column to NULL and update the existing records to be NULL as well.
If you are sure newsletters is the correct table name as #Ray said.
Try this:
$newsLetters = DB::table('newsletters')->get();

Resources