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
Related
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');
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 !!?
I'm wondering if it is possible to inherit/override constructors in child controllers in cakephp.
In my AppController.php
I have it like this:
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
$this->email = new CakeEmail();
$this->_constants = array();
$this->_constants['some_var'] = $this->Model->find( 'list', array(
'fields' => array( 'Model.name', 'Model.id' )
) );
}
and in my child controller SomeController.php, it inherits the parent constructor
public function __construct( $request = null, $response = null ) {
parent::__construct( $request, $response );
}
and when I tried to access $this->email and $this->_constants['some_var'] they both are null. But as soon as I put the code directly in SomeController.php instead of inheriting, it worked.
Did I do something wrong or this is simply not approachable for cake?
Also I tried the same with function beforeFilter(), same thing happened.
But it makes sense that each controller to have its own beforeFilter().
I wouldn't even try overriding the _construct' function of the appController. That's what thebeforeFilter,beforeRender` methods are for. It looks like you are just trying to pass vars to each controller from the appController. You can do that like so...
class AppController extends Controller {
var $_constants = array();
public function beforeFilter(){
$this->_constants[] = array('this', 'that', 'the other');
}
}
and in your model's controller you can access the variable like so...
class UsersController extends AppController {
public function add(){
pr($this->_constants);
}
}
It's a different story if you are trying to send the variables to the view (slightly). Just use the set method
class AppController extends Controller {
public function beforeFilter(){
$this->set('_constants', array('this', 'that', 'the other'));
}
}
and in any view you can just call the _constants variable with pr($_constants);. Because it is in the appController it should be available on every view.
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().