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');
}
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>";
Here are my tables
Schema::create('badge_user', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('badge_id')->references('id')->on('badges')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
Schema::create('badges', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->string('image')->nullable();
$table->integer('condition');
$table->timestamps();
$table->softDeletes();
});
Here are relationships
In BagdeUser modal
public function badge()
{
return $this->hasMany(Badge::class);
}
In Badge modal
public function badgeUser()
{
return $this->belongsTo(BadgeUser::class , 'badge_id');
}
In my resource
I have fetched all the data from the badge_user table and passed it in the resource
public function toArray($request)
{
return [
'badges' => new BadgeResource($this->badge),
];
}
BadeResource
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'image' => new MediaResource($this->getMedia('badge')->first()),
'condition' => $this->condition,
];
While fetching data o got this
Column not found: 1054 Unknown column 'badges.badge_user_id' in 'where clause' (SQL: select * from `badges` where `badges`.`badge_user_id` = 1 and `badges`.`badge_user_id` is not null and `badges`.`deleted_at` is null)
Now I want the badges associate with the user
The problem is that in your badge_user migration, you create foreign key badge_id which would mean that there is a relation Badge User N:1 Badge
But in your models you assign that BadgeUser has many Badges and Badge belongs to BadgeUser (which is Badge User 1:N Badge)
That is why laravel is looking for badge_user_id in query, because you defined the relationship the other way around.
Still tho you are probably doing M:N relations which you don't need to do manually.
You should use something like this (from Laravel docs)
return $this->belongsToMany(Role::class);
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)')
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();
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'));