I have issue that customer_id comes null when there is no data in the table. I know that there is a function IFNULL by using which I can change customer_id null to 0. So here is my query which is not working. checked a lot of related issues solved in the stackover flow but I could not find the solutino for my self if any one can help me with it will be kind of him.
it show me this error
"message": "Trying to get property of non-object",
customerController code is
public function store(Request $request)
{
//
try {
$this->validate($request,[
'name'=>'required',
'contact'=>'required|unique:Customers',
// 'contact'=>'required',
'address'=>'required',
'email'=>'required|string|email|max:191|unique:Customers',
]);
$getId = DB::table('Customers')->select('*', DB::raw('ifnull(id,0)'))->first();
$getfirst = $getId->id;
if($getfirst == 0)
{
$getfirst = 1;
$incId = $getfirst;
}
else{
$incId = $getfirst+1;
}
// $lastInsertedId= $Customer->id;
$Customer= Customer::create([
'name'=>$request['name']."-". $incId ,
'contact'=>$request['contact'],
'address'=>$request['address'],
'email'=>$request['email']
]);
return response()->json($Customer);
}
catch (Exception $e) {
return response()->json($e->getMessage(), 500);
}
}
customer table is
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->default("مشتری");
$table->integer('contact')->unique();
$table->string('address');
$table->string('email')->unique();
$table->softDeletes();
$table->timestamps();
});
}
IFNULL is used to check the field is nullable or not.
So it is not used to check a record exist or not.
You can use empty() to check the object is exist
$getId = DB::table('Customers')->first();
$getfirst = empty($getId)? 0 : $getId->id;
Try this
$getId = DB::table('Customers')->selectRaw(['*', 'IFNULL(id,0)'])->first();
I think you can write it as:
DB::raw('IFNULL(id, 0)')
Related
The Parent Model - User
public function posts() {
return $this->hasMany(Post::class);
}
The Child Model- Post
public function user_posts() {
return $this->belongsTo(User::class,"id");
}
Now in the Route, I was trying to print- Every post and the name of the admin -
Route::get("/admin/posts",function() {
$posts = Post::all();
foreach($posts as $post) {
$userId = $post->id;
$userName = Post::findOrFail($userId)->user_posts->name;
echo "<pre>
Title - $post->title
Content - $post->content
Author - <mark>$userName</mark>
</pre>";
}
});
By running this code it only prints only the first post of the admins and shows an error Trying to get property 'name' of non-object
Pulling out by single post id it prints the user data it works fine
Route::get("/admin_data_by/postsId",function() {
$postId = 1;
$userName = Post::findOrFail($postId)->user_posts->name;
echo "<pre>
Author - <mark>$userName</mark>
</pre>";
});
Migrations- User
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Migration- Post
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer("user_id")->unsigned()->nullable()->index();
$table->string("title");
$table->text("content");
$table->timestamps();
});
}
just change your route method to the following and and everything will work for you
$postId = 1;
$userName = Post::firstOrFail('id', $postId)->user_posts->name;
echo "<pre>
Author - <mark>$userName</mark>
</pre>";
you first get object and show parameters in object
please get data with below code
$user = Post::findOrFail($userId);
$post = $user->user_posts;
echo "<pre>
Title - $post->title
Content - $post->content
Author - <mark>$post->name</mark>
</pre>";
This question is similar to this question
I haven't changed the default autoIncrement from the table migration, however I noticed i couldn't get a model from the ID for a specific row. For the other rows it works fine. I cleared cache thinking it was a cache issue, but seems it is not.
Behaviour
I got records 1,..., 58, 59, 60
When i select a model
$object = Post::find(59);
// $object returns null but record exists
However i added another record via the app to check if the behaviour is the same, and the record from 60 is not null and it is the expected behaviour. Has anyone encountered this? If so what would be the best approach to overcome this.
I am using XAMPP v8.0.8 on Windows
Edit:
Post Model
class Post extends Model
{
use HasFactory,Searchable,SoftDeletes;
protected $fillable = [
'hash_id','user_id','location','subjects','request_type'
];
protected $casts = [
'location' => 'array',
'subjects' => 'array'
];
public function User()
{
return $this->belongsTo('App\Models\User');
}
public function searchableAs()
{
return 'posts';
}
}
Migration file
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('hash_id')->unique();
$table->integer('user_id');
$table->json('location');
$table->json('subjects');
$table->string('request_type');
$table->timestamps();
$table->softDeletes();
});
}
Assuming from soft deletes this happens if the record is deleted. Try looking in the deleted_at field on database.
I want to display all posts which like the user. OK. I can use this:
$user = User::where('slug', $user->slug)
->first();
dd($user->likes);
But it doesn't what I want to do. Which any post have to be accept by moderator (->where('accept', 1)) and orderign (->orderBy('created_at', 'desc')).
Who know how I can do that?
Currently I have 2 models. My relationships:
//Post
public function likes(){
return $this->hasMany('App\Like');
}
//Likes
public function post(){
return $this->belongsTo('App\Post');
}
//migrate of likes look like this
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');
$table->timestamps();
});
How I can solve my problem?
You could set up an M:N relationship between User and Post using Likes as pivot.
# User model
public function likes()
{
return $this->hasMany(Likes::class, 'user_id');
}
public function liked_posts()
{
return $this->belongsToMany(Post::class, 'likes', 'user_id', 'post_id');
}
# Likes model
public function post()
{
return $this->belongsTo(Post::class);
}
You could set it up like you have, User has many Likes belongs to Post.
// Using only likes and Likes's post relationship
$user = User::with(['likes.post' => function ($posts) {
$posts->where('accept', 1)->orderBy('created_at', 'desc');
}])->where('slug', $slug)->first();
Or you could use the M:N relationship.
// Using the liked_posts relationship
$user = User::with(['liked_posts' => function ($posts) {
$posts->where('accept', 1)->orderBy('created_at', 'desc');
}])->where('slug', $slug)->first();
I have referred all the other questions asked and did what they have told. Still i cant get rid of default_value error. I have added multiple connections. So i have 3 databases : Users , companya , companyb.
Company-A and Company-B has same structure.
Stocks have tag_no as primary key and i have specified it in model too.
Inside Stock model I have created a constructor to dynamically switch models based on users company.
Even after all this i keep getting this error.
I tried changing strict to false inside database.php but.. all the entries are showing value 0. So I stopped trying that.
So what can i do to solve this. Please help!
Below is my schemas:
For Users:
Schema::connection('mysql')->create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('company')->default('companya');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('user_type',50)->default('user');
$table->rememberToken();
$table->timestamps();
});
For company-A and company-B:
Schema::connection('companya')->create('stocks', function (Blueprint $table) {
$table->string('tag_no')->index();
$table->string('stock_type');
$table->timestamps();
});
Here is my Stock Model:
class Stock extends Model
{
protected $primaryKey = 'tag_no';
public $incrementing = false;
protected $fillable = [
'tag_no',
'stock_type',
];
public function __construct() {
if ( Auth::check() ) {
$this->connection = Auth::user()->company;
}
}
}
Code for store function:
public function store(Request $request)
{
if(Auth::check()){
if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) {
return back()->withInput()->with('errors', 'Tag number already used!');
}
$stock = Stock::create([
'tag_no' => $request->input('tag_no'),
'stock_type' => $request->input('stock_type'),
]);
}
if($stock){
return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
->with('success' , 'Stock created successfully');
}
return back()->withInput()->with('errors', 'Error creating new Stock');
}
Just changed create to insert and removed stocks parameter.
public function store(Request $request)
{
if(Auth::check()){
if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) {
return back()->withInput()->with('errors', 'Tag number already used!');
}
$stock = Stock::insert([
'tag_no' => $request->input('tag_no'),
'stock_type' => $request->input('stock_type'),
]);
}
if($stock){
return redirect()->route('stocks.index')
->with('success' , 'Stock created successfully');
}
return back()->withInput()->with('errors', 'Error creating new Stock');
}
My project have two role
admin
expert
admin must see all data of all city.
expert must see all data of own city after registered.
public function index()
{
$schools = SchoolsList::latest()->paginate(25);
$city_id = SchoolsList::where('city_id')->first();
$expert = Role::where('id', '=', 2);
if ($expert){
return view('Admin.inspection-failed.all', compact('schools')->where(($city_id)));
}
else{
return view('Admin.inspection-failed.all', compact('schools'));
}
}
Table of school
Schema::create('schools', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities');
$table->string('school_name');
$table->string('status');
$table->string('gender');
$table->string('notes');
$table->string('member_name');
$table->string('type');
$table->string('file_number');
$table->string('phone');
$table->string('address');
});
I want to when a expert login. Expert display data only own expert city.
I get this error.
Call to a member function where() on array
Error becomes in this codecompact('schools')->where(($city_id)); because compact('schools') it is equivalent ['schools' => $schools]. See documentation http://php.net/manual/en/function.compact.php. And in your case your code is equivalent ['schools' => $schools]->where(($city_id)).
For fix it you must be use
Short Answer
$schools = $schools->where('city_id' => $city_id->id);
return view('Admin.inspection-failed.all', compact('schools'));
Long Answer
$city = City::first(); // you must be fix it yourself
$expert = Role::where('id', '=', 2); // you must be change it
if ($expert) {
$schools = SchoolsList::latest()->paginate(25);
} else {
$schools = SchoolsList::where('city_id', $city->id)->latest()->paginate(25);
}
return view('Admin.inspection-failed.all', compact('schools'));