Laravel trying to store multi-data - php

I'm trying to store multi-data to my pivot table. I have CategoryUser table with category_id and user_id.
Store function
public function store(Request $request)
{
foreach ($request->userId as $key => $userId) {
$data = new CategoryUser();
$data->user_id = $userId;
$data->category_id = $request->categoryId[$key];
$data->save();
}
return redirect()->back();
}
In my Blade file i have name="categoryId[]" and name="userId[]".
However, it stores only one category_id. What am I doing wrong?

For 1 user ID case, loop through category ID array first.
public function store(Request $request)
{
foreach ($request->categoryId as $key => $categoryID) {
$data = new CategoryUser();
$data->user_id = $request->userId[0];
$data->category_id = $categoryID[$key];
$data->save();
}
return redirect()->back();
}

Related

No database entries when iterate array from database Laravel

protected function show()
{
$users = User::all();
$letters = Letter::with('user');
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = $letters->where(['user_id' => $user->id])->first();
if($userLetter){
//Here it shows that only the first user exists, returns null for the rest users.
}
}
}
We get an error when we sort the array with foreach.
No record is found in the database except the first.
For other entries, return null.
outside foreach no errors.
Just move your object inside the loop like below.
protected function show()
{
$users = User::all();
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = Letter::with('user')->where(['user_id' => $user->id])->first();
if($userLetter){
}
}
}
You would probably be better off using a letter relationship on the User.
On the User model you could do something like :
public function letter()
{
return $this->hasOne(Letter::class, 'user_id');
}
Then you could in the controller:
protected function show()
{
$users = User::with('letter')->get();
foreach ($users as $user) {
if ($user->letter) {
// do things
}
}
}

How to get one record by decrypting

I'm using an encrypt script. I can store data one by one as encrypt. And I can get all the table data by decrypting using below code.
public function alldata(Request $request)
{
$data = Contact::all();
return view('mail.list', ['data' => $data]);
}
Now, I have problem. I'm trying to get on record but it didn't decrypt.
Could someone please tell me what is wrong with my code below?
public function onerecord(Request $request)
{
$param = ['id' => $request->id];
$data = DB::select('select * from contacts where id = :id', $param);
return view('mail.one', ['data' => $data]);
}
UPDATES
This is my current code
public function one(Request $request)
{
$data = Contact::find($request->id);
return view('mail.one', ['data' => $data]);
}
my blade files
#foreach ($data as $val)
<tr>
<td>{{ $val->id }}</td>
</tr>
#endforeach
Result
using below code
public function one(Request $request)
{
$data = Contact::where('id',$request->id)->first();
return $request->all();
}
{
"id": "1"
}
One easy way is use laravel eloquent
public function onerecord(Request $request)
{
$data = Contanct::where('id',$request->id)->first();
return view('mail.one', ['data' => $data]);
}
or
public function onerecord(Request $request)
{
$data = Contanct::whereId($request->id)->first();
return view('mail.one', compact('data'));
}
both of them are same
Update:
public function onerecord(Request $request)
{
$data = Contanct::where('id',$request['id'])->first();
return view('mail.one', ['data' => $data]);
}
or
public function onerecord(Request $request)
{
$data = Contanct::whereId($request['id'])->first();
return view('mail.one', compact('data'));
}
Hope this is helpful

Complex query and getting results by slug instead of ID in laravel

I have complex query and relation which I'm not fully understand. I'm kind of new in Laravel. Anyway, I'm looking for a way to load this with slugs instead of ID's.
This is the function in the controller
public function index( $category_id)
{
$Category = new Category;
$allCategories = $Category->getCategories();
$category = Category::find($category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', $category_id)->where('parent_id','!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
$items = Item::whereIn('category_id',$array)->where('published', 1)->paginate(5);
} else {
$items = Item::where('category_id' ,$category_id)->where('published', 1)->paginate(5);
}
return view('list', compact('allCategories','items'));
}
Those are relations in the Model
public function item()
{
return $this->hasMany('App\Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->paginate(40);
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id );
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount( $category_id )
{
return Item::where('category_id', $category_id)->count();
}
This is what I have in my routes
Route::get('list/{category}', 'ListController#index')->name('list');
currently is loading urls like http://example.com/list/1 where 1 is the ID. I'm wonder if with current setup is possible to make it like, http://example.com/slug
I'm aware how slugs are working. I just can't understand how to use them in queries instead of ID's
You can use explicit Route Model Binding to grab your Category by slug before processing it.
In your RouteServiceProvider you need to bind the model:
Route::bind('category', function ($value) {
//Change slug to your column name
return App\Category::where('slug', $value)->firstOrFail();
});
Then, you can typehint the categories.
For example in your index method:
public function index(Category $category)
{
$Category = new Category;
$allCategories = $Category->getCategories();
//This line is obsolete now:
//$category = Category::find($category_id);
//...
}
Try to change your index function parameter from $category_id to $category_slug
Remove this line $Category = new Category;
And change this $category = Category::find($category_id);
To this: $category = Category::where('slug', $category_slug)->first();
*Assuming that you have a unique slug in category table

Laravel 5.1 get data from connected table

In my app admin users can create articles. Articles table is: ID | user_id | title ...
For every Article other user (which not admin) can post an offer and Offer table is: ID | user_id(not admin) | article_id | price ...
Now I need to get all users for an admin user which post Offer to their Article... I try:
public function userbase()
{
$id = Auth::user()->id;//get admin id
$articles = Article::where('user_id', $id)->get();//select all admin articles
foreach ($articles as $article) {
$users = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get(); //get all admin users
}
return $users;
}
but I get just: []
also my Model is:
Article:
public function offers() {
return $this->hasMany('App\Offer');
}
Offer:
public function user() {
return $this->belongsTo('App\User');
}
public function article() {
return $this->belongsTo('App\Article');
}
So how I can get all user details which was posted offer to an admin user?
UPDATE
I also try this:
$articles = Article::with([
'offers' => function($query) {
$query->orderBy('created_at', 'desc');
$query->with('user'); // if you want to eager load users for each offer too...
}
])->where('user_id', Auth::id())->get();
and I get this data:http://i.imgur.com/0kBVGrx.png
but how to access user data? I try ->get('user') but dont work...
2. UPDATE:
I also try:
public function userbase()
{
$articles = Auth::user()->articles()->get();
foreach ($articles as $article) {
$offers = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get();
}
foreach ($offers as $offer) {
$users = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}
but I get undefined variable users
Try this :
First, you may add an attribute 'isAdmin' in your User model.
public function userbase()
{
return Offer::select('users.*')
->where('users.isAdmin', false)
->join('articles','articles.id','=','offers.article_id')
->join('users','users.id','=','articles.user_id')
->where('articles.user_id', Auth::user()->id)
->orderBy('offers.created_at', 'desc')
->groupBy('users.id')
->get();
}
Updating Your solution :
public function userbase()
{
$articles = Auth::user()->articles;
foreach ($articles as $article) {
$offers = Offer::where('article_id',$article->id)->orderBy('created_at', 'desc')->get();
}
$users = array();
foreach ($offers as $offer) {
$users[] = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}

Laravel show data from key column not from id

I have this route:
Route::resource('articles', 'ArticlesController');
Route::get('articles/aukcija/{key}', 'ArticlesController#aukcija');
and I have this function in Controller:
public function show($id)
{
$article = Auth::user()->articles()->findOrFail($id);
return view('articles.show', compact('article'));
}
public function aukcija($key)
{
$article = Article::findOrFail($key);
return view('articles.show', compact('article'));
}
I need both of them... but how I can get Article with token stored in key column instead ID...
so when I write localhost:8888/article/1 and localhost:8888/article/aukcija/f4576ceusyfc674wr873cr48c7sefc to get the same article becouse article with ID=1 have key=f4576ceusyfc674wr873cr48c7sefc...
You could try this:
public function aukcija($key)
{
$article = Article::where('key', $key)->firstOrFail();
// or
$article = Article::where(compact('key'))->firstOrFail();
return view('articles.show', compact('article'));
}

Categories