Store data into database using request json string in laravel - json

I am having a table name Student ( id , name , division ). To store data into this table I am sending json string as a request to the api in laravel.
Request json string is,
{
"name":"abc",
"division":"a",
"city":"xyz"
}
Controller Code
public function registerStudent(Request $request){
$requestData = $request->json()->all();
$studentModel = Student::create($requestData);
}
Student Model
class Student extends Model
{
protected $fillable = [
'id', 'name','division'
];
}
When i execute this code , i get the following error,
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'city' in 'field list' (SQL: insert into `Student`...
now my question here is, in what way I can store the data into database from json request with having extra keys into json object/array.

You could use the collections only method.
public function registerStudent(Request $request){
$requestData = collect($request->json()->all())->only(['name', 'division']);
$studentModel = Student::create($requestData);
}

Related

TypeError: Cannot access offset of type string on string

In laravel I have created a session where I have stored a row of user table which include id, name and so on. I have created a condition where if the session exists then only access the ID stored in that table row via session.
And, when I run the code the session exists but when it comes to accessing the ID, it says "Cannot access offset of type string on string".
The following are the codes:-
Code where i have created a session:-
class UserController extends Controller
{
function login(Request $req)
{
$user= User::where(["email"=>$req->email])->first();
if(!$user || !Hash::check($req->password, $user->password))
{
return "username or password is not matched";
}
else{
$req->session()->put("user", "$user");
return redirect("/");
}
}
}
Code where m trying to access the ID via session:-
if ($req->session()->has("user"))
{
$cart = new Cart;
$cart->user_id = $req->session()->get('user')['id'];
$cart->product_id = $req->product_id;
$cart->save();
return redirect("/");
}
else
{
return redirect("/login");
}

cannot insert data in codeigniter 4

I want to insert registration data, I followed the existing tutorial, but got an error exception.
$users = new UsersModel();
$data = [
'name' => $this->request->getPost('name'),
'email' => $this->request->getPost('email'),
'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT)
];
$users->insert($data);
My Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UsersModel extends Model
{
protected $table = "users";
protected $primarykey = "id";
protected $returnType = "object";
protected $useTimestamps = true;
protected $allowedFields = ['name', 'email', 'password'];
}
throw the exception:
mysqli_sql_exception #1054
Unknown column 'updated_at' in 'field list'
The exception is
mysqli_sql_exception #1054
Unknown column 'updated_at' in 'field list'
Which strongly suggests that it is expecting a column called updated_at.
You have set protected $useTimestamps = true;
So as per the documentation:
$useTimestamps
This boolean value determines whether the current date is
automatically added to all inserts and updates. If true, will set the
current time in the format specified by $dateFormat. This requires
that the table have columns named ‘created_at’ and ‘updated_at’ in the
appropriate data type.
So you need to create the columns created_at and updated_at

cannot get the relationship data in laravel

this is my function
public function show($id)
{
$newproject = Newproject::find($id);
$data = [
'name' => $newproject->user->name
];
return $data;
}
newproject model
public function user()
{
return $this->hasOne(User::class,'user_id' ,'id');
}
it always getting the error
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
please help my to solve my problem please.
Check the relationship one-to-one reference
The foreign_key user_id is in newprojects table, you need to build the relationship like this:
User model:
public function newproject()
{
return $this->hasOne(Newproject::class,'user_id');
}
newproject model:
public function user()
{
return $this->belongsTo(User::class);
}
I think it should be something like this,
public function user()
{
return $this->hasOne(User::class,'id' ,'user_id');
}
It means id of users table match with current model's user_id column. And if you have proper naming convention according to laravel then you don't need to pass this extra params.
Laravel hasOne relation
Hope it helps:)
found the problem in my model
in user model
public function newproject()
{
return $this->belongsTo(Newproject::class,'user_id','id');
}
in newproject model
public function user()
{
return $this->hasOne(User::class,'id' , 'user_id');
}
thanks all

Column not found: 1054 Unknown column 'playlist_entity_assets.play_list_id&#039

I use three tables playlists, entityAssets, and playlistEntityAssets.
PlaylistEntityassets table has 2 columns playlist_id, asset_id referring to the other two tables. when I try to get data filter by playlist_id it gives me this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'playlist_entity_assets.play_list_id' in 'where clause' (SQL: select * from playlist_entity_assets where playlist_entity_assets.play_list_id = 3 and playlist_entity_assets.play_list_id is not null)
this is my get method. even though my table has a "playlist_id" column. this query calls for the "play_list_id" column.
public function show($subdomain, $id) {
$universe = Auth::user()->getCurrentUniverse();
$playlist = PlayList::find($id);
//return empty responce
if( $playlist == null){
return Response::json();
}
$playlistAssets = array();
$playlistEntityAssets = $playlist->playlistEntityAssets;
foreach($playlistEntityAssets as $plEntityAsset){
$asset = $plEntityAsset->entityAsset;
$plAsset = ['asset' => $asset ];
$playlistAssets[] = $plAsset;
}
return Response::json($playlistAssets);
}
I want to fitler all enityAssets data filter by playlist_id in the "playlistEntityAssets" table.
use Illuminate\Database\Eloquent\Model;
class PlaylistEntityAssets extends Model
{
protected $table = 'playlist_entity_assets';
public function user()
{
return $this->belongsTo('asset');
}
public function universe()
{
return $this->belongsTo('Universe');
}
public function playlist(){
return $this->belongsTo('Playlist', 'playlist_id');
}
public function entityAsset(){
return $this->belongsTo('EntityAsset', 'asset_id');
}
I already fixed the problem. The answer is to put the exact column name in the playlist model.
class PlayList extends Eloquent{
public function playlistEntityAssets()
{
return $this->hasMany('PlaylistEntityAssets', 'playlist_id' );
}
}

Laravel API pass to Vuejs query join nested transaction and order Ttbles

I am creating a shopping cart and i have 3 tables here as you can see in the image. first is the products, orders and last the transactions, all products that has been ordered will be place in order table along with transaction id whoever belongs to that transaction, and transaction table would record the total balance and change and i want to fetch it in database using laravel query builder and convert it to json like in the 2nd image below, i hope my explanation is not that confusing. Thanks in advance guys :)
Follow the steps below:
1.Creating models and adding relationship between them.
You can create models for transaction , order & product using phpartisan.
php artisan make:model Transaction
php artisan make:model Order
php artisan make:model Product
configure them according to your mysql tables structure.
Adding relationships.
Transaction Model
public function order(){
return $this->hasOne(Order::class, 'transaction_id', 'id');
}
Order Model
public function transaction(){
return $this->belongsTo(Transaction::class);
}
public function products(){
return $this->hasMany(Product::class, 'id', 'product_id');
}
Product Model
public function order(){
return $this->belongsTo(Order::class);
}
2.Creating a controller to handle the results.
You can create a controller using phpartisan.
php artisan make:controller TransactionController -r
Setting up our controller.
public function TransactionDetails($transactionID){
$transaction = Transaction::where('id',$transactionID)->firstOrFail();
$order = $transaction->order;
$products = $order->products;
$result = array();
$result['transaction'] = $transaction;
$result['transaction']['order'] = $order;
$result['transaction']['order']['products'] = $products;
return response()->json($result);
}
This should work and give you your desired output , if any error occurs let me know.
generating models.
php artisan make:model Transaction
php artisan make:model Order
php artisan make:model Product
TransactionModel
public function orders()
{
return $this->hasMany(Order::class, 'transaction_id', 'id');
}
ProductModel
public function orders()
{
return $this->hasMany(Order:class, 'product_id', 'id');
}
OrderMode
public function product()
{
return $this->belongsTo(Product::class, 'product_id', 'id');
}
public function transaction()
{
return $this->belongsTo(Transaction::class, 'transaction_id', 'id');
}
You can create a ResourceCollection to generate your desired JSON output.
php artisan make:resource TransactionCollection
this will create a ResourceCollecion in app\Http\Resource\TransactionCollection
TransactionCollection
class TransactionCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
$transactions = [];
foreach($this->collection as $transaction) {
$jsonTransaction = [
'id' => $transaction->id,
'date' => $transaction->transaction_date,
'total' => $transaction->transaction_total,
'change' => $transaction->transaction_change,
'orders' => []
];
foreach($transaction->orders as $order) {
$product = $order->product;
array_push($jsonTransaction['orders'], [
'id' => $order->id,
'product_name' => $product->product_name,
'category' => $product->product_category,
'price' => $order->order_price,
'quantity' => $order->order_quantity
]);
}
array_push($transactions, $jsonTransaction);
}
}
}
TransactionController
public function getAllTransactions()
{
// this will return your desired json result as you posted in the question.
return TransactionCollection::make(Transaction::all());
}