i'm working on a E-commerce like project where users can upload multiple images of a particular product, i have a one-to-many relation where many images has one description and price. so on the homepage i need to call a single image out of the total uploaded and also fetch the descrition of the image, so when view button is clicked the user can see the rest of the image sliding.
upload Controller
public function store(Request $request)
{
$request->validate([
'farm_name'=> 'required',
'farmer_name'=>'required',
'min_order'=>'required',
'qty'=>'required',
'product_package'=>'required',
'descr'=>'required',
'images' => 'required',
'images.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
//'' => 'image|mimes:jpeg,png,jpg,gif,svg|max:6048',
]);
$input = new Product;
$input->farm_name = $request->farm_name;
//$input->user_id = Auth::user()->id;
$input->farmer_name = $request->farmer_name;
$input->tel = Auth::user()->tel;
$input->farm_adrs = Auth::user()->adrs;
$input->state = Auth::user()->state;
$input->email = $request->email;
$input->qty = $request->qty;
$input->descr = $request->descr;
$input->product_package = $request->product_package;
$input->catr = $request->catr;
$input->lga = $request->product_name;
$input->amount = $request->amount;
//$input->img = $request->images;
//dd($input);
$input->save();
foreach($request->file('images') as $imageFile){
$image = new Image;
$imageName = time().rand(1,99).'.'.$imageFile->extension();
$imageFile->move(public_path('images'), $imageName);
$image->images_id = $input->id;
$image->name = $imageName;
$image->save();
}
return back()
->with('success','Your Product is succesfully Uploaded.');
}
//show image this where i have problem
public function index(){
$products = Product::all();
foreach($products as $product){
$product_id = $product->id;
$images = Image::find($product_id);
}
return view('app.index', compact('products', 'images'));
}
First of all u re saving product id as image_id on image table. Is this your correct column? if you are using image_id to save related product id, then change the index code to
public function index(){
$images=[];
$products = Product::all();
foreach($products as $product){
$product_id = $product->id;
$images[$product_id] = Image::where('image_id',$product_id)->get();
}
return view('app.index', compact('products', 'images'));
}
it will give you all the images from all product set upped with index of product id.
in a better way you can directly join the table. it will reduce the no. of executing query.
i am facing a problem. i am new in laravel . i created many to many relation in my application.but it's shown error. please check bellow code :
Error
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `category_post` (`category_id`, `created_at`, `post_id`, `updated_at`) values (1, 2019-11-09 17:00:29, ?, 2019-11-09 17:00:29))
Post Model code :
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
Category model code
public function posts()
{
return $this->belongsToMany('App\Post')->withTimestamps();
}
PostController Code
public function store(Request $request)
{
$this->validate($request,[
]);
$image = $request->file('image');
$slug = str_slug($request->name);
if(isset($image))
{
$imageName = $slug.'-'.time().uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('posts/'))
{
Storage::disk('public')->makeDirectory('posts/');
}
$postImage = Image::make($image)->resize(1600,1066)->stream();
Storage::disk('public')->put('posts/'.$imageName,$postImage);
}else{
$imageName = 'default.png';
}
$posts = new Post();
$posts->user_id =Auth::id();
$posts->title = $request->title;
$posts->slug = $slug;
$posts->body = $request->body;
$posts->image = $imageName;
$posts->categories()->attach($request->categories);
$posts->tags()->attach($request->tags);
$posts->is_approved = true;
if(isset($request->status))
{
$posts->status = true;
}else{
$posts->status = false;
}
$posts->save();
// $posts->tags()->attach($request->tags);
Toastr::success('Post Is created successfully','Success');
return redirect()->route('admin.posts.index');
}
My create.blde.php file code is okey all request goes appropriately but above error shown when i submit my post..Thank in advance
You have a belongs to many relationship between posts and categories. In order to create that relationship on your pivot table, you must have a category_id and a post_id.
This line in your code:
$posts->categories()->attach($request->categories);
is correct, but you are trying to attach the categories to the post object before you have saved it. Thus, the unsaved post object has no id yet.
Save your post, and then attach the categories with the attach() method you have already written.
Same thing with your tags() attachment. Stick it in after you have saved the post object.
I have a factory of posts and a factory of posts_images, a post can have many images, I did create a seeder for posts that look like this.
$posts = factory(App\Models\Post::class, 100)->create()
->each(function($post) {
$post->images()->saveMany(factory(App\Models\PostsImage::class, 3)->make());
});
I want to create 100 posts and that each post have 3 images, this kind of work, the problem is when the image is created
I want the image to be created from a base_64 string and saved in certain directory but I need the id of the post so I can create the folder where it will be created.
$factory->define(App\Models\PostsImage::class, function (Faker $faker) {
//this does not get me the id
$id = factory(\App\Models\Post::class)->make()->id;
$name = time();
$b64_image = \Config::get('constants.seed_image');
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $b64_image));
if(!file_exists(public_path('images/eventos/'.$id.'/'))) {
mkdir(public_path('images/noticias/'.$id.'/'));
}
file_put_contents(public_path('images/noticias/'.$id.'/'.$name.'.jpg'), $data);
return [
//
'image' => $name,
'order' => $id + 1
];
});
The only line that seems not to be working is
$id = factory(\App\Models\Post::class)->make()->id;
I did try using create instead of make, but this create more rows in the post table, and I don't want that.
Is there a way to pass the post id to the images factory?
The best option will be to create the directory in the posts seeder, since you have the access to the $post object when a Post is created. Try something like this:
$posts = factory(App\Models\Post::class, 100)->create()
->each(function($post) {
//id is available on the $post object created
$id = $post->id;
$name = time();
$b64_image = \Config::get('constants.seed_image');
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $b64_image));
if(!file_exists(public_path('images/eventos/'.$id.'/'))) {
mkdir(public_path('images/noticias/'.$id.'/'));
}
file_put_contents(public_path('images/noticias/'.$id.'/'.$name.'.jpg'), $data);
$post->images()->saveMany(factory(App\Models\PostsImage::class, 3)->make());
});
What I do usually in this situation is to get the last record of the created parent object.
$factory->define(App\Models\PostsImage::class, function (Faker $faker) {
// get last record of Post
$id = \App\Models\Post::orderBy('id', 'desc')->first()->id;
$name = time();
$b64_image = \Config::get('constants.seed_image');
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $b64_image));
if(!file_exists(public_path('images/eventos/'.$id.'/'))) {
mkdir(public_path('images/noticias/'.$id.'/'));
}
file_put_contents(public_path('images/noticias/'.$id.'/'.$name.'.jpg'), $data);
return [
//
'image' => $name,
'order' => $id + 1
];
});
I have a many to many relationship between departments and users my pivot table is department_user. I wanted to select all the department_name depending of the user's department using groupBy method to merge all the department_name into one. See below my statement.
$departmentRecipient = DB::table('users')->select('departments.department_name', 'users.id')
->join('department_user', 'users.id', '=', 'department_user.user_id')
->join('departments', 'department_user.department_id', '=', 'departments.id')
->groupBy('departments.department_name')
->get();
Result using die and dump.
As you can see here I have an id of 4 under "Department of Engineering". My main problem is it doesn't fetch all the id under "Department of Engineering". But in my SQL I have id of 5 not only 4. How can I solve this problem? Any help would greatly appreciated. Please see result below.
Output:
This is the output of my list. I wanted to get all the users id belongs to the specific option for the user. But if I choose "Department of Engineering" it only gets the id of 4 not 5. I wanted to get 4 and 5 once.
Controlller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
return view ('document.create')->with('departmentRecipient', $departmentRecipient);
}
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
'content' => 'required',
'category' => 'required',
'recipient' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
$user = Auth::user();
foreach($request->recipient as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}
Model
User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Department
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
View
<div class = "form-group">
<label for = "recipient" class = "control-label">Recipient:</label>
<select name = "recipient[]" multiple class = "form-control select2-multi" id = "myUserList">
#foreach ($departmentRecipient as $list)
<option value = "{{ $list->id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
From your given code it seems you are not using Eloquent ORM, you are doing it using Query Builder.
If you don't have a performance concern right now you can do it using separate queries. Like-
$departmentRecipient = DB::table('departments')->all();
foreach($departmentRecipient as $department){
$department->users = DB::table('department_user')->where('department_id',$department->id)->pluck('user_id');
}
But the better way is to use the eloquent with relationships. Define the many to many relationship in your eloquent model of Users and Departments (assuming you have eloquent model for them). You will find details about eloquent relationships at laravel documentation.
Update:
From the update of your post it is actually pretty easy to do what you want. If your Request contains the selected department id then you can do the following:
public function postDocuments(Request $request)
{
$document = new Document();
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
//get the users list of the selected department id
$selected_department = $request->department_id; //this must be included in your POST data
$users = DB::table('department_user')->where('department_id',$selected_department)->pluck('user_id');
//now you have the list of the users id
foreach($users as $user){
// do what you need here
}
}
Update 2:
Following controller code might work for you.
Controller:
public function getDocuments()
{
// I am suggesting here to change the '$departmentRecipient' to '$departmentlist', as it is more meaningful. Also in your view
$departmentlist = DB::table('departments')->get();
return view ('document.create')->with('departmentlist', $departmentlist);
}
public function postDocuments(Request $request)
{
//same as you have till the $document->save()
....
....
//then do this
$recipients = array();
$departments = $request->recipient;
foreach($departments as $department){
$users = DB::table('department_user')->where('department_id',$department)->pluck('user_id');
$recipients = array_merge($recipients, $users);
}
//now you have a complete list of the users from selected departments
//Do as you intend to like this
$user = Auth::user();
foreach($recipients as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}
I'm currently using the below code to insert data in a table:
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
I want to return the last ID inserted but I don't know how to get it.
Kind regards!
After save, $data->id should be the last id inserted.
$data->save();
$data->id;
Can be used like this.
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try this
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:
DB::getPdo()->lastInsertId();
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId([
'email' => 'john#example.com',
'votes' => 0
]);
Refer: https://laravel.com/docs/5.1/queries#inserts
For anyone who also likes how Jeffrey Way uses Model::create() in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillable for mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId() but unfortunately this does not respect the $fillable whitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's create method just wraps the save method (what #xdazz cited above), so you can still pull the last created ID...
public function store() {
$input = Request::all();
$id = Company::create($input)->id;
return redirect('company/'.$id);
}
**** For Laravel ****
Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as
$user = new User();
$user->name = 'John';
$user->save();
// Now Getting The Last inserted id
$insertedId = $user->id;
echo $insertedId ;
There are several ways to get the last inserted id. All are based on what method do you used when inserting. In your case you can get last Id like the following:
$data->save();
$data->id;
For others who need to know how can they get last inserted id if they use other insert methods here is how:
Using create() method
$book = Book::create(['name'=>'Laravel Warrior']);
$lastId = $book->id;
Using insertGetId()
$id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id;
Using lastInsertId() method
$lastId = DB::getPdo()->lastInsertId();
Reference https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/
In laravel 5: you can do this:
use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
private $user;
public function __construct( User $user )
{
$this->user = $user;
}
public function store( UserStoreRequest $request )
{
$user= $this->user->create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password'])
]);
$lastInsertedId= $user->id;
}
}
This worked for me in laravel 4.2
$id = User::insertGetId([
'username' => Input::get('username'),
'password' => Hash::make('password'),
'active' => 0
]);
Here's an example:
public static function saveTutorial(){
$data = Input::all();
$Tut = new Tutorial;
$Tut->title = $data['title'];
$Tut->tutorial = $data['tutorial'];
$Tut->save();
$LastInsertId = $Tut->id;
return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}
Use insertGetId to insert and get inserted id at the same time
From doc
If the table has an auto-incrementing id, use the insertGetId method
to insert a record and then retrieve the ID:
By Model
$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail#gmail.com"]);
By DB
$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail#gmail.com"]);
For more details : https://laravel.com/docs/5.5/queries#inserts
For insert()
Example:
$data1 = array(
'company_id' => $company_id,
'branch_id' => $branch_id
);
$insert_id = CreditVoucher::insert($data1);
$id = DB::getPdo()->lastInsertId();
dd($id);
Here is how we can get last inserted id in Laravel 4
public function store()
{
$input = Input::all();
$validation = Validator::make($input, user::$rules);
if ($validation->passes())
{
$user= $this->user->create(array(
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
));
$lastInsertedId= $user->id; //get last inserted record's user id value
$userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
$user->update($userId); //update newly created record by storing the value of last inserted id
return Redirect::route('users.index');
}
return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
}
Although this question is a bit dated. My quick and dirty solution would look like this:
$last_entry = Model::latest()->first();
But I guess it's vulnerable to race conditions on highly frequented databases.
After saving model, the initialized instance has the id:
$report = new Report();
$report->user_id = $request->user_id;
$report->patient_id = $request->patient_id;
$report->diseases_id = $request->modality;
$isReportCreated = $report->save();
return $report->id; // this will return the saved report id
You can easily fetch last inserted record Id
$user = User::create($userData);
$lastId = $user->value('id');
It's an awesome trick to fetch Id from the last inserted record in the DB.
After
$data->save()
$data->id will give you the inserted id,
Note: If your autoincrement column name is sno then you should use
$data->sno and not $data->id
After saving a record in database, you can access id by $data->id
return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)
In Laravel 5.2 i would make it as clean as possible:
public function saveContact(Request $request, Contact $contact)
{
$create = $contact->create($request->all());
return response()->json($create->id, 201);
}
For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).
You can use following code:
if($data->save()) {
return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
}
You can do this:
$result=app('db')->insert("INSERT INTO table...");
$lastInsertId=app('db')->getPdo()->lastInsertId();
$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name
return Response::json(['success' => true,'id' => $recId], 200);
For get last inserted id in database
You can use
$data = new YourModelName;
$data->name = 'Some Value';
$data->email = 'abc#mail.com';
$data->save();
$lastInsertedId = $data->id;
here $lastInsertedId will gives you last inserted auto increment id.
The shortest way is probably a call of the refresh() on the model:
public function create(array $data): MyModel
{
$myModel = new MyModel($dataArray);
$myModel->saveOrFail();
return $myModel->refresh();
}
You can also try like this:
public function storeAndLastInrestedId() {
$data = new ModelName();
$data->title = $request->title;
$data->save();
$last_insert_id = $data->id;
return $last_insert_id;
}
Here it is how it worked for me, family_id is the primary key with auto increment I am using Laravel7
public function store(Request $request){
$family = new Family();
$family->family_name = $request->get('FamilyName');
$family->family_no = $request->get('FamilyNo');
$family->save();
//family_id is the primary key and auto increment
return redirect('/family/detail/' . $family->family_id);
}
Also in the Model Family file which extends Model, should have the increment set to true otherwise the above $family-->family_id will return empty
public $incrementing = true;
Using Eloquent Model
$user = new Report();
$user->email= 'johndoe#example.com';
$user->save();
$lastId = $user->id;
Using Query Builder
$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe#example.com']);
After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.
Response code will be:
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
You can get last inserted id with same object you call save method;
$data->save();
$inserted_id = $data->id;
So you can simply write:
if ($data->save()) {
return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}
public function store( UserStoreRequest $request ) {
$input = $request->all();
$user = User::create($input);
$userId=$user->id
}
Using Eloquent Model
use App\Company;
public function saveDetailsCompany(Request $request)
{
$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
// Last Inserted Row ID
echo $createcompany->id;
}
Using Query Builder
$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
echo $createcompany->id;
For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel