Laravel PHP, getting clicked link class - php

I have a html5 table which is dynamically made from database items and it contains links, e.g. delete icon, which is in link tags . I want to be able to click the delete icon and know, which item I want to delete. I have set class of the link the same as the relevant database items ID, but I cant read the class from the controller, after I click the link. Is there a method of doing that in PHP Laravel? Or maybe you could suggest a way better way to accomplish that? This seems a way off tactic for this.

If each row on the table represents a row on database, so your link could contain the id from database.
For example, a user table.
Row 1 => Link /users/delete/1
Row 2 => Link /users/delete/2
Row 3 => Link /users/delete/3
By doing it this way, you can know for sure which one is called.
On your routes file, if you are not using Route::resource(), you should have something like this:
Route::get('users/delete/{id}', 'UsersController#destroy');
And in your destroy method:
public function destroy($id)
{
// your logic here
}

Format your links as:
If for example you are listing all items using foreach:
#foreach( $items as $item )
{{$item->name}}
#endforeach
Inside routes.php
Route::get('item/delete/{id}', 'ItemsController#deleteItem');
inside ItemsController.php define the following function
public function deleteItem($id) {
$item = Item::get($id);
if( !$item ) App::abort(404);
$item->delete();
return Redirect::to('/');
}
and I am assuming you have your model in Item.php
class Item extends Eloquent {
protected $table = 'items';
}
and your items table has id and name columns

Related

Unable to do laravel relationships using laravel 5.5

I am facing issue regarding storing ids and display their values from two different table i have 1 table business_master and other table is page_master i have combine business_name column with page_url column which are available on page_master table if i add my business and page first time its successfully combine these two values as one business can have many pages and if i only add page 2nd time i am unable to see business_url with page_url column.
My Page Model:
class PageList extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id', 'page_url', 'page_name'];
public function business()
{
return $this->hasOne('App\Business','business_id');
}
}
and in my view:
<td>{{optional($value->business)->business_url}}.spikesales.io/{{$value->page_url}}</td>
This is my first time out if i add business_url and page_url
hussain.spikesales.io/house
and then if i add only page the out put is something like that
.spikesales.io/hello
one business can have many page it should attach business_ url also but i am unable to find solution:
Any help will be highly appreciated!
public function pageListHere()
{
$list = PageList::all();
return view('page-list',compact('list'));
}
You have to change your controller code like this:
$list = PageList::select('*');
$list->with(
array('business'=>function($query){
$query->select('*');
}));
$pageList = $list->get();
return view('page-list',compact('pageList'));
The varialbe $pageList will be having all the rows of that table along with related Business table rows.

Route with multiple Id's (Laravel 5.2)

I want a URI like this
http://localhost:8000/category/1/3
The first id is Category_id and second is Food_id.
My route is:
Route::get('category/{Category_id?}/{Food_id?}', 'DetailsController#categ');
And in Controller I have:
public function categ($Category_id,$Food_id)
{
$category = Categories::with('food')->findOrFail($Category_id);
$food = Food::with('restaurant','categories')->findOrFail($Food_id);
return view('category', compact('category','food'));
}
But it gives error Missing argument 2 for App\Http\Controllers\Detailscontroller::categ().Can anyone tell where is the problem.I am new to laravel.What I want to do is first shows food items based on category_id and then shows the deatails of foods according to food_id.
For showing relevant category of foods,in my view I have
#foreach ($Category as $categories)
{{$categories->CategoryName}}
#endforeach
and it shows me food items.Then I want when I click on any food item it shows me detail based on food_id. so my nxt view look like:
#foreach ($category->food as $food)
{{ $food->FoodName }}
#endforeach
The comment Anish left was correct, however, you main problem will come when you're trying to find models with null. To get around this you could have something like:
public function categ($Category_id,$Food_id)
{
$category = is_null($Category_id) ? []: Categories::with('food')->findOrFail($Category_id);
$food = is_null($Food_id) ? [] : Food::with('restaurant','categories')->findOrFail($Food_id);
return view('category', compact('category','food'));
}
NB They may be more errors in your view file depending on if you're trying to access.
However, I would go with a much more RESTful approach: https://laravel.com/docs/5.2/controllers#restful-resource-controllers
Essentially, this would mean having a controller for you Categories:
public function index() {
//Code to get all categories (if you have a lot you may want to paginate them)
}
public function show($Category_Id) {
$category = Categories::with('food')->findOrFail($Category_id);
//etc
}
and then a controller for you Foods with just a show() method:
public function show($Food_Id) {
$food = Food::with('restaurant','categories')->findOrFail($Food_id);
}
OR depending on how you set your route up you could also include the category as well if you need to (but if it's just a one2Many relationship it might be redundant) so you would have
public function show($category_ID, $Food_Id) //etc
Your routes would then be set up like this:
Route::get('categories', 'CategoriesController#index');
Route::get('categories/{$category_id}', 'CategoriesController#show');
//Assuming you go with the first option - something like:
Route::get('foods/{$food_id}', 'FoodsController#show');
//Assuming you go with the section option for Foods
Route::get('categories/{$category_id}/{$food_id}', 'FoodsController#show');
Obviously, the above is just an example so feel free to set you controllers/routes up how you like.
If you do end up going down the RESTful route (recommended) you then might want to look at: https://laravel.com/docs/5.2/routing#route-model-binding
Hope this help!

Laravel simplify a database query with relations

I'm just started to work with Laravel and think its a pretty good framework.
But there is a lot to learn and i can mostly find everything in the user guide except this part:
I'm trying to get items from my database they are sorted with a category id that relates to a other table item_catagories in this table are stored:
id
name
parent
In my url of the website I use the name of the category instead of the id.
http://example.com/catagory/subcatagory
when subcatagory has a value I want to search for the related items.
I now have it like this:
if($subcategory){
$foo = ItemCategories::where(['group' => $category, 'name'=> $subcategory])
->get()[0]->id;
$data['products'] = Items::where('category_id', $foo)->get();
}
but there must be a much simpler way to get the same results.
I hope someone can help me to understand how I can do it better
Edit
I forgot to add the relation code:
The item class:
public function categorie(){
return $this->hasOne('App\ItemCategories');
}
The categorie class:
public function items(){
return $this->belongsTo('App\Items');
}
You can use Laravel Eloquent's relationships for this. On your category model:
public function items() { return $this->hasMany('Items'); }
Once you've done that, on a category, you can do $category->items to fetch all of its related items.
Incidentally, when you do this:
->get()[0]
you can just do this:
->first()
If you wish to bring your results already populated, one way to do this is:
$foo = ItemCategories::where(['group' => $category, 'name'=> $subcategory])->with('items')->first();

store variables on user model laravel 4

my user model has 3 fields: username, password and category_id
so when i auth the auth object will have all of the 3 variables, but i want to add the name of the category that is on other model
and i get like:
$category = Category::find(Auth::user()->category_id);
$category_name = $category->name;
so the question is who can i add $category_name to the Auth::user() object, in order to retrive it every time he is logged like this:
Auth::user()->category_name
i try Session::put("category_name","Category 1") when you loggin, but when i close the windows and open it by the last closed windows, it delete that variable.
i want to store the variable since the person login, untill the person logout, but if the person has logged in and close the window and then the person re open the page the variable must be filled
You can use Eloquent Accessors
In User model
public function setCategoryNameAttribute()
{
$categoryID = $this->category_id;
$category = Category::find($categoryID);
return $category->name;
}
You can access category name like
Auth::user()->category_name
try this
in your User model add the following function
EDIT try this
public function category_name()
{
return \Cache::remember('category_' . $this->id , 60, function()
{
return $this->belongsTo('App\Category')->get();
});
}
now everytime you use
Auth::user()->category_name
you will have the name
this will eco the name in your View
{{ Auth::user()->category_name }}
NOTE : this code is not the best solution even if it worked for you, this is open for changes, i just want you to get the point that if you want to access something via Auth::user()->getname you have to add the getname function in the User model
and by the way can you show us the relation you set in you model? because that would make it easier
an exemple
if you have something like this in ur model(hasone)
public function category() {
return $this->hasOne('category');
}
you can do this
Auth::user()->category->name

How to chain DB relationships in Laravel (multiple has_many?)

I'm using Laravel, which is awesome, but I'm stuck on an issue with the database.
Let's say we have three tables, like so:
TABLE 1: pages
id | route | title
TABLE 2: elements
id | page_id | type
TABLE 3: content
id | element_id | data
I'd like to do a single selection for the page that will in turn select all of the elements with that page id, and for each of the elements it should select all of the content rows with the element id.
I want to have a static load_by_route($route) function in the Page model that, when called, will use the route to load and return the page info as well as the elements and content as described above. Ideally it would return a single object/array with all of this info.
Basically, I'm not sure how to chain the has_many() calls together so that I get the two-level relationship.
Look into eager loading. This should do what you want.
class Page extends Eloquent {
public function elements()
{
return $this->has_many( 'Element' );
}
}
class Element extends Eloquent {
public function contents()
{
return $this->has_many( 'Content' );
}
}
class Content extends Eloquent {}
$page = Page::with( array( 'elements', 'elements.contents' ) )->first();
https://laravel.com/docs/master/eloquent-relationships#eager-loading
Collin James answer gives you one object with all the data. I came here because I just wanted to iterate over all contents that belong to a page. Here is how you get such a collection:
$page = Page::with('elements.contents.element')->has('elements.contents');
$contents = [];
foreach ($page->elements as $element) {
$contents = $element->contents->merge($temp);
}
The with makes sure that you use eager loading and the has makes sure that we only iterate over elements with content.
From each content element you can get the element info from the belongsTo relationship that we also received with eager loading:
class Content extends Eloquent
{
public function element()
{
returh $this->belongsTo('\App\Page');
}
}

Categories