Hello im really newbie on Laravel. So I really need some help.
I need help on my table. The view from my table contains App\Models\Store and App\Models\Product, but I just want every App\Models\Store and App\Models\ Product to only show as Store and Product
This is my code on my table
<td>
<label>
<a href="{!! route('reports.tolink', [$report->id]) !!}" target="_blank">
{!! $report->reportable_type !!}
</a>
</label>
</td>
$report->reportbale_type it contains App\Models\Store and App\Models\Product
and this is my Controller
public function toLink($id)
{
$report = $this->reportRepository->findWithoutFail($id);
//get Store Name
$name = Store::where('id','=',$report->reportable_id)->pluck('name')->all();
$storename = $name[0];
//get Store ID
$idstore = Store::where('id','=',$report->reportable_id)->pluck('id')->all();
$storeid = $idstore[0];
if(empty($report))
{
Flash::error('Report not found');
return redirect(route('reports.index'));
}
$report_type = class_basename($report->reportable_type);
return redirect(env('FRONTEND_URL') ."/".str_slug($report_type)."/$storeid/".str_slug($storename));
}
and this is my table
There are few ways you can do this.
You can use Reflection to get the short name
(new \ReflectionClass($report->reportable_type))->getShortName()
You can explode by \ and get the last item
array_pop(explode('\\', $report->reportable_type))
Using substr and strrpos
substr($report->reportable_type, strrpos($report->reportable_type, '\\') + 1)
You can use one of the above methods and add a getter to your Report model.
public function getReportableTypeNameAttribute()
{
return (new \ReflectionClass($this->reportable_type))->getShortName();
}
which will allow you to call $report->reportable_type_name in your views.
Related
I am selecting the multiple id of classes in creating leadtype via explode,how can i get all the selected id of classes in dropdown in edit function
Classes table
id 1 name class one
id 2 name class two
id 3 name class three
Leadtype table
id 1 class_id 1,2,3,
id 2 class_id 1,2
id 3 class_id 2,1
I am saving only id of classes in leadtype table but when i edit i want
all the value selected instead of id
my route
Route::get('admin/leadtypes/form', 'LeadTypesController#form'); add
Route::post('admin/leadtypes/post', 'LeadTypesController#update'); store
Route::get('admin/leadtypes/form/{id}', 'LeadTypesController#editForm'); edit
Add function
public function form() {
$classes = Classes::pluck('name','id');
return view('leadtypes.form',$data,compact('classes'));
}
My store/update function
public function update(Request $request)
{
$data = \Input::except(array('_token')) ;
$rule=array(
'name' => 'required',
);
$validator = \Validator::make($data,$rule);
if ($validator->fails())
{
return redirect()->back()->withInput()->withErrors($validator->messages());
}
$inputs = $request->all();
if(!empty($inputs['id'])){
$item = LeadTypes::findOrFail($inputs['id']);
}else{
$item = new LeadTypes;
}
if(is_array($request->name)){
$item->name = implode(',', $request->name);
}
$item->status = $inputs['status'];
$item->save();
flash('success','record_added_successfully', 'success');
return redirect('admin/leadtypes');
}
edit function
public function editForm($id)
{
$item = LeadTypes::findOrFail($id);
$data['active_class'] = 'Lead type';
$data['title'] = getPhrase('Lead type');
$classes = Classes::pluck('name','id');
$item->name = explode(',', $item->name);
return view('leadtypes.form',$data,compact('item','classes'));
}
My view dropdown
{!! Form::select('name[]', $classes, !empty($item->name) ? $item->name : explode(',',old('name')) ,['class' =>'form-control ' ,'required'=>'true','multiple'=>'true']); !!}
I think you may be pushing the LaravelCollective Form::() method to a place it's not happy with. It is a bit finicky to start, and there are a few issues with what you have above.
The $item->name is actually a string as stored, I think. If it is set in the DB, it is going to come through to your last line of code as a string:
!empty($item->name) ? $item->name : explode(...)
You need to explode the DB-stored string in the FIRST part of your operation above as well, to get this to match whatever the $classes array is for the second parameter in that same statement. String <--> array won't work, and thus won't ever allow for a value to be selected from the model.
I'm pretty sure this will solve it. However, I would also possibly reconsider your architecture on this. Storing those arrays of IDs in a single field (and a field named singular 'name') is a little confusing, and is also making life difficult for you. Perhaps consider pulling those LeadTypes into their own belongsToMany relationship with their own sub table. Then you can just store the two ids and simplify everything. If that works -- but the above should answer your question.
I have a form that a user enters and takes the entry and queries the database and returns to a view. I have managed to get one query working but when trying to work on another query it returns an undefined variable error in the view. See below:
Routes
Route::get('/shopsales', 'shopsalescontroller#index');
Controller
class shopsalescontroller extends Controller
{
public function index()
{
$storeNum = request('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',compact('result'));
}
}
shopsales view
<section>
<center><h1><STRONG>Query Data</STRONG></h1></center>
<ul>
#foreach ($result as $results)
<li>Report Name = {{ $results->ReportName}} | Report ID = {{ $results->ReportID}} | Store Number = {{ $results->StoreNumber}} | Store Name = {{ $results->StoreName}} | Week Number = {{ $results->WeekNumber}} |
Year = {{ $results->Year}} | PerfumeName = {{ $results->PerfumeName}} | Units Sold = {{ $results->UnitsSold}} | Sales = {{ $results->Sales}}
</li>
<br>
#endforeach
</ul>
</section>
I have used the exact code for the query that is working, struggling to understand why this is not.
try this
in App\Route
Route::resource('/shopsales','ShopSalecontroller');
This routes the following actions: index, create, store, show, edit, update and destroy.
add this function to shopsales model
public function scopeNumber($query, $number){
if($number != null){
$query->where('storeNumber','=', "$number");
}
}
in ShopSalesController index:
public function index(Request $request){
$result = shopsales::get()->number($request->storeNumber)->all();
return view('shopsales',compact('result'));
}
Remember to have in the index view a form with the field storeNumber
public function index()
{
$storeNum = request('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',['result'=>compact('result')]);
}
Change your controller code like above.
Also check if $result is not null.
Try something like this
public function storeCheckout(Request $request) {
$storeNum=$request->get('storeNum');
$result = shopsales::where('StoreNumber','=',$storeNum)
->get();
return view('shopsales',compact('result'));
}
Solved, though sorry for wasting your time, some of my views should of had a capital letter in them, fixed that cleared the view cache and now i have the queries.
in action index
change var $result to $results
in view index
#foreach ($results as $result)
#endforeach
I'm trying to make a simple "friends" system, by storing each friend id in a single column as a string separated with a comma.
I want to get the users by id and store them in an array:
public function getFriends() {
$friendids = explode(',', $this->friends);
$friends = [];
foreach ($friendids as $id) {
$friends[] = User::findOrFail($id);
}
return $friends;
}
So I can do this in my view:
#foreach ($user->getFriends() as $friend)
<p>Friend ID: {{ $friend->id }}</p>
<p>Friend Username: {{ $friend->username }}</p>
#endforeach
But I think I can't use findOrFail in the user model or what am I doing wrong?
To use the findOrFail($id) method, you should invoke the object type you want to get. Example:
foreach ($friendids as $id) {
$friends[] = User::findOrFail($id);
}
Although there's an existing answer, I wanted to provide an alternative solution that I personally feel is a better long-term solution.
Firstly, saving friends as an comma separated list isn't going to scale very well. It also massively limits the ability for you to do things such as 'friends of friends', and other more complex queries.
Really, you should have two tables, users and friends.
User model
public function acceptedFriends()
{
return $this->hasMany('App\Friend')->where('accepted', true);
}
public function pendingFriends()
{
return $this->hasMany('App\Friend')->where('accepted', false);
}
Now, when a friend request is rejected, you can simply delete the record in the Friends table.
Loading a user with their friends:
$user = User::find($id)->with('acceptedFriends')->firstOrFail();
Loading a user's friend requests:
$users = Friends::where('accepted', false)->where('target_user', $userId)->get();
You might want to also check out https://stackoverflow.com/a/25057320/972370. It's written by someone who is very well known in the Laravel community for advanced Eloquent usage.
I made 2 simple mistakes:
1) I removed User object from findOrFail()when looking for the mistake I made
2) I had specified user id's (friends) that did not exist in the databse, causing an error
I also improved the code a bit, by adding an optional parameter to get only x amount of users:
// App/User.php
public function getFriends($friends_to_get = null) {
$friendids = explode(',', $this->friends);
$friends = [];
$i = 0;
foreach ($friendids as $id) {
if (is_numeric($id)) {
$friends[] = User::findOrFail($id);
}
if (isset($friends_to_get) && $i < $friends_to_get) {
++$i;
}
if (isset($friends_to_get) && $i == $friends_to_get) {
break;
}
}
return $friends;
}
Now you can do something like this in your view:
#foreach ($user->getFriends() as $friend)
<p>Friend ID: {{ $friend->id }}</p>
<p>Friend Username: {{ $friend->username }}
#endforeach
Or if you want to get, for example, 6 friends only, you can do: $user->getFriends(6)
In my case, $user is the user of who's profile I'm currently viewing. If you want, you could also get your friends only, by doing Auth::user()->getFriends()
/Edit: Added is_numeric check in the foreach loop. This way you don't have to worry about first and last element in the column having an extra comma. Since explode adds an extra value to the array, if there's a comma in the end of the friends column. Now you can just add or remove x, from/to the column every time and not worry about fetching an object, that does not exist.
Terms table
term_id
name
slug
Term_taxonomy table
term_taxonomy_id
term_id
description
i want to show all record like "term_id , name , description
my Term model
public function TermTaxonomy(){
return $this->hasOne('TermTaxonomy');
}
my TermTaxonomy model
public function Term(){
return $this->belongsTo('Term');
}
my route
$term = new Term;
$categories = $term->all(['term_id', 'name']);
foreach($categories as $category){
echo $category->term_id . " " . $category->name . " " . "description of term_id should here" ;}
trying this code but Error Undefined property: Illuminate\Database\Eloquent\Collection::$TermTaxonomy
$e = new Term;
$f = $e->all(['term_id','name']);
echo $f->TermTaxonomy->description;
}
with the above code i want to return all description of each term_id, but i am confusing why i can show description if the object just 1 , like this code below
$a = new Term;
$b = $a->all(['term_id','name'])->find(8);
echo $b->TermTaxonomy->description . "<br>"; // work return description of $b;
so what is exactly one to one relationship function ? is one to one only work when the object just 1 ?
what about in my case ? is my logic wrong to show all description using relationship method ? then what must i do to show term id , name , description lists ?
thanks in advance, i am totally newbie in laravel.
You can't access relationships on collections directly. I mean, what would you even expect? All descriptions as comma separated list?
Instead you just access the relation when you loop over all of them anyways. (That's probably in the view so I'm going to use Blade syntax in this example)
#foreach($terms as $term)
{{ $term->term_id }} {{ $term->name }} {{ ($term->TermTaxonomy ? $term->TermTaxonomy->description : '') }}
#endforeach
($term->TermTaxonomy ? $term->TermTaxonomy->description : '') is a shorthand if. It means:
if($term->TermTaxonomy){
echo $term->TermTaxonomy->description;
}
else {
echo '';
}
It works because if the Term has no TermTaxonomy assigned, $term->TermTaxonomy will be null. With this code we only try to access ->description if TermTaxonomy exists and can therefore avoid a Trying to get property of non-object exception.
Attention: While this works you definitely should eager load the TermTaxonomy relationship. You see if we leave it like that, each time you do $term->TermTaxonomy a DB query will be run. To avoid n+1 queries, use with to eager load relationships:
$terms = Term::with('TermTaxonomy')->get(['term_id','name']);
Regarding your question in the comments, yes you can limit the fields that you select from term_taxonomy:
$terms = Term::with(['TermTaxonomy' => function($q){
$q->select('term_id', 'description');
}])->get(['term_id','name']);
Just make sure you include the columns necessary to make the relationship (in this case term_id)
If you do a $e-all, you get an array with the TermTaxanomies. When you do a specific search (->find(8)) you only get that object with id = 8.
All you need to do is use a foreach or use an index number:
$f = $e->all(['term_id','name']);
foreach($f as $tax){
var_dump($tax);
}
Or
$f = $e->all(['term_id','name']);
var_dump($f[1]);
var_dump($f[4]);
I think that should work.
oops! Looks like you're trying to implement raw php code into Laravel. Please get rid of that , follow the instructions bellow.
make a Route:
Route::get('/term' , array('uses' => 'TermsController#showTerm'));
Now make a Controller named TermsController.php and try something like bellow:
<?php
class TermsController extends BaseController {
public function showTerm(){
$terms = Term::all();
return View::make('show_term.blade.php')->with('terms' , $terms);
}
}//class ends
Now make a Model named Term.php :
<?php
class Terms extends \Eloquent{
protected $fillable = array();
protected $table = 'terms'; //terms is your database table name
}?>
Now make a show_term.blade.php :
#extends(layouts.master)
#section('content)
foreach($terms as term){
{{$term->id}} , {{$term->name}} , {{$term->slug}}}
#stop
if you don't have the layouts.master then create a layouts folder inside you View folder. Then create a master.blade.php write the basic html and inside the body try like this:
<div class="container">
#yield('content')
</div>
Thank you . Let me know if you need anything else.
hi :) im parsing my database in a table with pagination !!
this is my controller
$theme = Theme::all();
$questions = questionList::paginate(10);
$the = "";
return View::make('home.home')
->with('user',Auth::user())
->with('theme', $theme)
->with('the' , $the)
->with('questions',$questions);
and my view i have {{ $questions->links(); }} under my table and it's working fine !!
the thing is that i have a list of themes to sort data in the table so when i click on divertisement i get divertisement data.
the problem is that when i paginate it return to the get request and give me all the data !! what is the problem thx :)
To add a filter/sort you also need to add that in a where clause in your query and also you need to append the query string in your pagination links. For example:
public function showPosts()
{
$questions = app('questionList');
if($filter = Input::get('filter')) {
$questions = $questions->where('theme', $filter);
}
$questions = $questions->paginate(10);
if(isset($filter)) {
$questions->appends('filter', $filter);
}
return View::make(...)->with(...);
}
In your view you need to create links to this method (Probably using a route name or url) with filter query string. So, for example:
Divertisement
SomethingElse