can i know where is my fault
Error
insert into `images` (`product_id`, `image`, `updated_at`, `created_at`) values (?, 1656838354.png, 2022-07-03 08:52:34, 2022-07-03 08:52:34)
My Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image' , 'product_id'
];
public function product()
{
return $this->belongsTo('App\Product' , 'product_id');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description',
'image',
'detail',
'price',
'quantity'
];
public function image()
{
return $this->hasMany('App\Image');
}
}
My Controller
public function store(Request $request)
{
$request->validate([
'image'=>'required|mimes:jpg,png,jpeg|max:4096',
]);
$newImgName = time() . '.' . $request->image->extension();
$request->image->move(public_path('multiple_images'), $newImgName);
$image = Image::create([
'product_id' => $request->id,
'image' => $newImgName,
]);
return redirect()->route('products.index')
->with('msg','Record has been inserted successfully');
Related
i'm new to laravel and trying to build an api for a login using sanctum.
I followed documentation, and a few tutorials but i've encountered an error where the token function is not accessible by my user class even when using HasApiToken.
here is my user model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'alt_id',
'country_id',
'birth'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'type',
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function country()
{
return $this->hasOne(Country::class);
}
}
[this is the error message][1]
[1]: https://i.stack.imgur.com/QzGK9.png
I also already checked the route in config/auth.php and it is App\Models\User::class
I've solved that problem by adding $user->tokens()->delete(); into my AuthController#logout,
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller
{
public function logout(User $user){
$user->tokens()->delete();
return [
'message' => 'Logged out'
];
}
}
And User model looks like this.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
//some code
];
protected $hidden = [
//some code
];
protected $casts = [
//some code
];
}
I am working on a laravel app where i have a user(organizer) who post an event ,and other users can comment on this event .
I am trying to make notifications system in laravel 8 between the organizer and the users when commenting on these event !
but i get this error (Call to a member function notify() on null).
This is my class :
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewCommentPosted extends Notification
{
use Queueable;
protected $user;
protected $event;
public function __construct($user, $event)
{
$this->user = $user;
$this->event = $event;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'user' => $this->user->name,
'eventTitle' => $this->event->title,
'eventId' => $this->event->id
];
}
This is storefunction() in my controller :
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Comment;
use App\Notifications\NewCommentPosted;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function store(Event $event)
{
request()->validate([
'content' => 'required|min:5'
]);
$comment = new Comment();
$comment->content = request('content');
$comment->user_id = auth()->user()->id;
$event->comments()->save($comment);
$event->user->notify(new NewCommentPosted(auth()->user(), $event));
return redirect()->route('events.show', [$event->id, $event->title]);
}
Any help please !!?
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into posts (title, body, updated_at, created_at) values (?, ?, 2019-10-14 17:41:00, 2019-10-14 17:41:00))
controller (CRUD) controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\post;
class postcontroller extends Controller
{
public function store(Request $request)
{
$add = new post;
$add->title= $request->input('title');
$add->body= $request->input('body');;
$add->save();
session()->flash('msg','new post added successfully!');
return redirect()->route('posts.show',$add->id);
}
Model (post model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class post extends Model
{
protected $fillable = ['title', 'body'];
}
view ->(it just a from using laravelcollective )
It looks like you are sending null value for the title and to catch out the validation errors earlier on in your application, you should consider introducing some validation in your controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\post;
class postcontroller extends Controller
{
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'body' => 'required',
]);
$add = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);
session()->flash('msg','new post added successfully!');
return redirect()->route('posts.show', $add->id);
}
Make sure you have set the title and body fields in your form correctly
<form><!-- / Dont forget the action, crf and other required attr of form -->
<input type="text" name="title">
<textarea name="body"></textarea>
</form>
Learn more about form validation at https://laravel.com/docs/master/validation#validation-quickstart
Let's say that I had the following API set up:
Controller:
<?php
namespace app\modules\v1\controllers;
use yii;
class ResourceController extends \yii\rest\ActiveController
{
public $modelClass = 'app\modules\v1\models\Resource';
}
Model:
use yii;
class Resource extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'ResourceTable';
}
public function fields()
{
return [
'id' => 'ResourceID',
'title' => 'ResourceTitle',
];
}
}
where my table only has the two columns, ResourceID and Title.
When I try a GET request on the API, it works fine and returns the list of resources (or single resource in the case of resource/{id}) with the aliased field names. But when I try to POST to create a resource, I want to use the aliased field names (e.g. title instead of ResourceTitle). The problem is that the default CreateAction supplied by Yii does $model->load(), which looks for the field names in the table. If I use the aliased names then it returns an error. If I use the table field names, it works fine.
So my question is, is there a way to expose resource attributes to the end user where the field names (using the fields() function) are the same for reading and creating? If possible, I'd like to avoid writing my own CreateAction.
It's necessary to add rules for new virtual properties, if you want to $model-load() save parameters to them
class OrganizationBranch extends BaseOrganization{
public function rules()
{
return array_replace_recursive(parent::rules(),
[
[['organizationId', 'cityId'], 'safe'],
]);
}
public function fields() {
return ['id',
'cityId' => 'city_id',
'organizationId' => 'organization_id',
'address',
'phoneNumbers' => 'phone_numbers',
'schedule',
'latitude',
'longitude',
];
}
public function extraFields() {
return ['branchType', 'city'];
}
public function getOrganizationId() {
return $this->organization_id;
}
public function setOrganizationId($val) {
$this->organization_id = $val;
}
public function getCityId() {
return $this->city_id;
}
public function setCityId($val) {
$this->city_id = $val;
}
}
You can create getters/setters for alias.
public function getTitle(){ return $this->ResourceTitle; }
public function setTitle($val){ $this->ResourceTitle = $val ; }
With Yii php framework, I use inheritance.
In my AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'0'=>Yii::t('default','No'),
'1'=>Yii::t('default','Yes'),
);
}
In my object who extends AbstractModel, I have this method:
public function attributeLabels()
{
return array(
'username' => Yii::t('user', 'email'),
);
}
In a view file, I use:
<?php echo CHtml::activeLabel($model, $model->property);?>
But I never show 'No' or 'Yes' from asbtractModel. If I put all in my model it works. But I want to use inheritance.
How can I concat parent attributeLabels with current model attributeLabels?
Simply merge the return value of the parent method in MyObject (model class):
public function attributeLabels() {
return array_merge(
parent::attributeLabels(),
array(
'username' => Yii::t('user', 'email'),
)
);
}
You may also use CMap::mergeArray().