I'm developing rest api in laravel, here im trying to post array data in database, but i could not figure out how to do it, can some one guide me in this ? i'm new to laravel
ProductdetaisController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\productdetails;
class ProductdetailsController extends Controller{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return productdetails::all();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'productname' => 'required',
'productid' => 'required',
'productdescription' => 'required',
'productimage' => 'required',
'productinvoice' => 'required',
]);
return productdetails::create($request->all());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return productdetails::find($id);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$productdetails = productdetails::find($id);
return $productdetails->update($request->all());
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
return productdetails::find($id)->delete();
}
}
productdetails.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class productdetails extends Model
{
use HasFactory;
protected $fillable = ['productname', 'productid', 'productdescription', 'productimage', 'productinvoice'];
}
2021_09_25_075455_create_productdetails_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductdetailsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('productdetails', function (Blueprint $table) {
$table->id();
$table->string('productname');
$table->string('productid');
$table->string('productdescription');
$table->array('productinvoice'); <----- here i want to store array of data ------>
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('productdetails');
}
}
example for array of data
[{productquantity: '5', productprice: '5', productgst: '5', productname: 'xyz'}, {productquantity: '5', productprice: '5', productgst: '5', productname: 'ABC'}]
How to post such kind of above data in the data base ?
Model::create() doesn't work like that. You should loop over the array and create rows individually.
Laravel docs on this method
Also, your validation won't work. Docs on array validation
Try this: (save it to database)
$productinvoice =json_encode( $request->your_array_json_data );
...save it to database.
When you want to use It inside client side You should parse It to array of json data.
Like this: (use it inside client side part)
JSON.parse($productinvoice)
When You want to use it inside backend part after retrieve it from database.
This is how You could convert it to php array : (use it inside backend part)
$productinvoice = json_decode($productionDetails->productinvoice, true);
Related
hopefully someone can enlighten me on this bug. Laravel 8. I am replicating a simple blog from this url: https://www.codewall.co.uk/laravel-crud-demo-with-resource-controller-tutorial/
It seems like sometimes you do these tutorials but laravel 8 is slightly different. What am I missing here? Any suggestions would be greatly appreciated!
Getting error when going to /students & a /students/create urls , I am getting different errors for
/students (index) error -
Error
Class 'App\Student' not found
It doesn't like the create route either which is weird because I have store method in StudentController.
/students/create (create) error -
Action StudentController#store not defined. (View: C:\xampp\htdocs\laravel\lara-blog2\blog\resources\views\students\create.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$students = Student::all();
return view('students.index', compact('students','students'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('students.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
Student::create($input);
return redirect()->route('students.index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$student = Student::findOrFail($id);
return view('students.show', compact('student','student'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view('students.edit', compact('student','student'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$student = Student::findOrFail($id);
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'age' => 'required|numeric',
'email' => 'required|email',
]);
$input = $request->all();
$student->fill($input)->save();
return redirect()->route('students.index');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::findOrFail($id);
$student->delete();
return redirect()->route('students.index');
}
}
As you are using Laravel 8, all models now are located in App\Models directory in App directory as previous versions, so you need to update your import statement to be
use App\Models\Student;
Read more about Models new directory in Laravel Release Notes Here
In Laravel 8, all models now are located in App/Models so use
use App\Models\Student;
From Laravel 8, all models are now located in the App\Models directory in the App directory as in previous versions, so you need to update your import statement to be
App\Models\Student; instead of App\Student;
I try to make library of pdf files. which i want to store pdf title-name and file name also upload this pdf in project storage. but server show me this error.I can't understand what can I do.
Method App\Http\Controllers\Elibrary::save does not exist.
my error message
this is my elibrary controller file which i chech filename and store file name in database also stored in public/images location
I find this code on this linkuload file tutorial
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Elibrary;
class ElibraryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request){
$elibrary = Elibrary::orderBy('id','DESC')->paginate(5);
return view('e-library',compact('elibrary'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'efile' => 'required|max:4000',
]);
if($file= $request->file('file')){
$name = $file->getClientOriginalName();
if($file->move('images', $name)){
$elibrary = new Post;
$elibrary->efile = $name;
$elibrary->save();
return redirect()->route('e-library');
};
}
$elibrary = new Elibrary([
'title' => $request->get('title'),
'efile' => $request->file('file'),
]);
$elibrary->save();
return redirect()->route('e-library');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This is my route file code
Route::post('/store', 'Elibrary#store')->name('store');
this is e-library.blade.php file from
<form action="/store" method="post" enctype="multipart/form-data">
#csrf()
<div class="form-group">
<input type="text" class="form-control"name="title" placeholder="Name">
</div>
<div class="form-group">
<input type="file" class="form-control"name="efile" >
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-send-message" >
</div>
</form>
this is my model file of Elibrary.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Elibrary extends Model
{
public $fillable = ['title','efile'];
}
this is my migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateElibrariesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('elibraries', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('efile');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('elibraries');
}
}
How i can show this pdf with the help show function in show.blade.php
You're creating new instances of Elibrary in your controller methods. Elibrary is a controller class but it looks like you're treating it as a model.
Maybe try changing all of your new Elibrary() to new Post since it looks like that might be what you're trying to accomplish.
If thats the case, you will also need to make efile fillable in your Post model.
$elibrary = Post::orderBy('id','DESC')->paginate(5);
So I am having a bit of an interesting problem. I am trying to build a forum for my website. I am trying to create a test that ensures registered users can submit new forum threads. Now, regardless of what I do, the test always ends up at the login paghe, even though I am logged in.
Here is something interesting, however, when I attempt to dd() the thread immediately after creation, Laravel seems to "skip over" the dd command and I end up with the "Thread title not found on the login page" error. I can dd() the $request object and that prints out fine, however, it seems after creating a new Thread model does Laravel skip over the dd($thread) command and I end up getting the login page once again.
I am pulling my hair out. Why is this happening?
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
use App\Thread;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
class CreateThreadsTest extends TestCase
{
use DatabaseMigrations;
function test_an_authenticated_user_can_create_new_forum_threads() {
$this->be(factory('App\User')->create());
$thread = factory('App\Thread')->make();
$this->post('forum/threads', $thread->toArray());
// you are missing this line
$this->get($thread->path())->assertSee($thread->title)->assertSee($thread->body);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Thread;
class ThreadsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$threads = Thread::latest()->get();
return view('threads.index', compact('threads'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$thread = Thread::create([
'user_id' => auth()->id,
'title' => $request->title,
'body' => $request->body
]);
return redirect($thread->path());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Thread $thread)
{
return view('threads.show', compact('thread'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model
{
protected $guarded = [];
public function path() {
return "/forum/threads/" . $this->id;
}
public function replies() {
return $this->hasMany(Reply::class);
}
public function creator()
{
return $this->belongsTo(User::class, 'user_id');
}
public function addReply($reply) {
$this->replies()->create($reply);
}
}
When you make a new model using the factory helper, it doesn't have an ID
for example
So $thread->path() will return just "/forum/threads/" which is not what you want
You have to make the request to the location from the response or query the newly created Thread record
public function test_users_can_create_statuses()
{
$this->be(factory('App\User')->create());
$thread = factory('App\Thread')->make();
$response = $this->post('/forum/threads', $thread->toArray());
$this->get($response->headers->get('Location'))
->assertSee($thread->title);
->assertSee($thread->body);
}
I am new to couchbase and laravel. I am developing an entry form. I am using couchbase as database and in the back-end i am using laravel. when ever i try to insert data in the couchbase, although the query run, but it prints the data on the screen, rather than it stores in the database. Please help me in this issue
This is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
//
protected $table = '';
protected $primaryKey = 'id';
public $timestamps = false;
public static $couchbase_bucket = 'default';
public static $couchbase_doc = 'doc1';
protected $fillable = [
'id',
'name',
'father_name',
'constituency' ,
'seat_type',
'profession' ,
'deprtment' ,
'cabinet_post',
'party',
'date_of_birth',
'religon' ,
'marital_status',
'gender' ,
'education',
'present_contact',
'permanent_contact'
];
public static function create(array $attributes = array()){
die(print_r($attributes));
$value = [
'id' => intval($attributes['id']),
'name' => $attributes['name'],
'father_name' => $attributes['father_name'],
'constituency' => $attributes['constituency'],
'seat_type' => $attributes['seat_type'],
'profession' => $attributes['profession'],
'deprtment' => $attributes['department'],
'cabinet_post' => $attributes['cabinet_post'],
'party' => $attributes['party'],
'date_of_birth' => $attributes['date_of_birth'],
'religon' => $attributes['religon'],
'marital_status' => $attributes['marital_status'],
'gender' => $attributes['gender'],
'education' => $attributes['education'],
'present_contact' => $attributes['present_contact'],
'permanent_contact' => $attributes['permanent_contact'],
];
$key = 'insert:and:delete';
$result = \DB::connection('couchbase')->table(self::$couchbase_bucket)->key($key)->upsert($value);
return $result;
}
public static function all($columns = array()){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->get();
// DB::connection('couchbase')
// ->table('testing')->where('whereKey', 'value')->get();
}
public static function one($id){
return \DB::connection('couchbase')->table(self::$couchbase_bucket)->where('id',$id)->get();
}
}
And the controller is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Member;
class memberController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$memberdata = Member::all();
return view('member.index')->withuserdata($userdata);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('member.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$input = $request->all();
Member::create($input);
//return redirect('member/index');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
in App/Abstracts/ folder I have following file
1.Transformer.php
<?php
namespace App\Abstracts;
use eventsTransformer;
abstract class Transformer
{
public function transformCollection(array $item)
{
return array_map([$this ,'transform'],$item->toArray());
}
public abstract function transform($event);
}
2.eventsTransformer
<?php
namespace App\Abstracts;
class EventTransformer extends Transformer
{
public function transform($event)
{
return [
'event'=> $event['event'],
'date' => $event['date'],
'e_code'=> $event['eventcode'],
'country'=> $event['country'],
'city'=> $event['city']
];
}
}
Now In my Controller I am using them like this
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\ResponseFactory;
use App\Abstracts\eventsTransformer;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Event;
class EventsapiController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
//use EventTransformer;
protected $eventTransformer;
public function __construct(EventTransformer $EventTransformer){
$this->$eventTransformer = $EventTransformer; // replace 'collector' with whatever role you need.
}
public function index()
{
//
$events = Event::All();
$response = array();
return response()->json([
'data'=>$this->eventTransformer->transform($events)
],200);
//return $response['data']=$events;
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
$event = Event::find($id);
if(!$event)
{
return response()->json([
'error'=> 'Event does not exist',
'code' => 'e101'
],404);
}
return response()->json([
'data'=>$event->toArray()
],200);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
I am getting following error
ReflectionException in Container.php line 790: Class App\Http\Controllers\EventTransformer does not exist
Can any one help me out with this
MyQuestion is the same what How to include abstract in Laravel5
Thanks
You are getting this error because you misspelled namespace.
Instead of:
use App\Abstracts\eventsTransformer;
you should use:
use App\Abstracts\EventTransformer;
in your EventsapiController