i want to show the total of amount in the home view blade
(table = payments , colon = amount)
i tested another method by route , this it work fine but the result show in /test of course:
Route::get('/test', function(){
$total = DB::table('payments')
->where('status', '=', 'success') //this for collect only the success payments
->sum('payments.amount');
return $total; // work fine the result is correct
});
but my purpose is to display this result inside the home view
by move the function from the previous code from route to controller and call it in the view
for the controller i have Homecontroller but the function index is aleardy used , so i create new function in this controller i try this
public function show(){
$total = DB::table('payments')
->where('status', '=', 'success')
->sum('payments.amount');
return view('home' , $total);
}
for routing i put this
Route::get('/home', 'HomeController#show');
i try this inside the view but didnt work :
<h1>{{$total}}</h1>
You can use with()
public function show(){
$total = DB::table('payments')->where('status', '=', 'success')
->sum('payments.amount');
return view('home')->with('total', $total);
}
according to documentation :
The second argument is an "array" of data that should be made available to the view.
try :
return view('home' , ['total' => $total]);
or use ->with('key',$value) :
return view('home')->with('total', $total);
you can also use compact() function, it is an inbuilt function in PHP and used to create an array using variables:
return view('home' , compact("total"));
You can send total variable result with compact function to view like
below.
return view('home' , compact('total'));
// You can call it in home.blade like this
//for example
#if(isset($total ))
<li>{{ $total }}</li>
#endif
I have modified default auth method in controller which redirects user after custom login to set_password page. The problem is I can redirect it well to the desired page but I need to simultaneously pass two dynamic variables which are returned through querying database, which I am unable to pass with redirect.
My modified controller method is as follows:-
protected function authenticated(Request $request, $user)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return redirect()->route('set_password',['activated_up' => $activated_up, 'showuser' => $showuser]);
}
I know that to pass a variable to an view, I need to use the compact method like follows:-
return view('set_password', compact('activated_up', 'showuser'); but it cant be done with redirect.
The way I have redirected means I am passing parameters to route in the controller method, but I need to pass variables to the redirected view instead of parameters. How to achieve that?
protected function authenticated(Request $request, $user)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return redirect()->route('set_password',['activated_up' => $activated_up, 'showuser' => $showuser]);
}
you can use With
return redirect()->route('set_password')->with('data', ['some kind of
data']);
in your view
#if (session::has('data'))
The data is {{ session::get('data') }}
#endif
Tried as described in the answer by Kuldeep Mishra but could not achieve it though, anyways I found a workaround to achieve my desired output. What I did is changed my authenticated method to this:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('set_password');
}
I only redirected to the set_password route from the above method and made new method in the controller to show the view with the compacted variables like this:-
public function setPasswordForm(Request $request)
{
$activated_up = User::where('id_user',Auth::user()->id_user)
->where(function($query) {
$query->where('activated_up', '=', '1')
->orWhere('activated_up', '=','0');
})
->get(['activated_up']);
$showuser = UserProfile::where('id_user',Auth::user()->id_user)->first();
return view('set_password', compact('activated_up', 'showuser'));
}
And a small change in route web.php file:-
Route::get('/set_password', 'Controller#setPasswordForm')->name('set_password');
So finally I was able to redirect to desired page with the desired view loaded with dynamic variables.
I have two routes for web middleware in my laravel app listed below:
Route::get('package/{slug}','GetPublicController#tourDetail')
->name('single');
And
Route::get('/trips/{category}','GetPublicPageController#getBycategory')
->name('getBycategory');
The first route works well but second route doesn't. The second route is in conflict with the first route as it tries to get view of first route, causing error and app to breakdown.
Method for 1st route:
public function tourDetail($slug)
{
$tour = Tour::where('slug', '=', $slug)
->first();
$itineraries = Itinerary::where('tour_id','=', $tour->id)
->orderBy('id', 'asc')->get();
$depature_dates = $tour->datePrice()->FixedDates($tour->id, date('m'),date('Y'))->get();
return view('public.tour.tour-detail')
->withTour($tour)
->withItineraries($itineraries)
->withDepatures($depature_dates);
}
And method for 2nd route
public function getByCategory($category)
{
$query = Tour::whereHas('category', function($r) use($category) {
$r->where('tcategories.name','=', $category);
});
return view('public.pages.category-list')
->withResults($query);
}
It would be very helpful if anyone could suggest the best approach to resolve this issue.
Thank you.
You have to call ->get() on the query in getByCategory.
I am calling getting_started route after successfully login :
protected $redirectTo = '/getting_started';
Here is my getting_started route code :
Route::get('/getting_started','UserController#getting_started');
And controller code :
public function getting_started()
{
$id= Auth::id();
$user = DB::table('user_profiles')->where('user_id', '=', $id)->first();
if($user->dashboard_access == 0)
{
DB::table('user_profiles')
->where('user_id', $id)
->update(['dashboard_access' => 1]);
return view('user.getting_started');
}
return view('user.dashboard');
}
It works perfectly and show in url :
http://localhost:8080/getting_started
Now I actually want that if user.dashboard view is call it show in url like :
http://localhost:8080/dashboard`
And on getting_started view show :
http://localhost:8080/getting_started
It is possible to call dashboard route instead of :
return view('user.dashboard');
My dashobard route is :
Route::get('/dashboard',['middleware' => 'auth', function () {
return view('user.dashboard');
}]);
What I understand it is that you are looking for is this function
return redirect()->route('dashboard');
It's my understanding of your question which can be wrong. Maybe you are asking something else.
That called Redirection and especially you want to Returning A Redirect To A Named Route, you route called user.dashboard so you could redirect to it using redirect()->route(route_name) :
return redirect()->route('user.dashboard');
Hope this helps.
I am trying to create a page where I can see all the people in my database and create edits on them. I made a form where I fill in the data from the database of certain fields.
I would like to navigate trough them by a Next and Previous button.
For generating the next step I have to take the ID larger than the current one to load the next profile.
For generating the previous step I have to take the ID smaller than the current one to load the previous profile.
My route:
Route::get('users/{id}','UserController#show');
Controller:
public function show($id)
{
$input = User::find($id);
// If a user clicks next this one should be executed.
$input = User::where('id', '>', $id)->firstOrFail();
echo '<pre>';
dd($input);
echo '</pre>';
return View::make('hello')->with('input', $input);
}
View:
The buttons:
Next
What is the best approach to get the current ID and increment it?
Below are your updated controller and view files derived from #ridecar2 link,
Controller:
public function show($id)
{
// get the current user
$user = User::find($id);
// get previous user id
$previous = User::where('id', '<', $user->id)->max('id');
// get next user id
$next = User::where('id', '>', $user->id)->min('id');
return View::make('users.show')->with('previous', $previous)->with('next', $next);
}
View:
Previous
Next
// in your model file
public function next(){
// get next user
return User::where('id', '>', $this->id)->orderBy('id','asc')->first();
}
public function previous(){
// get previous user
return User::where('id', '<', $this->id)->orderBy('id','desc')->first();
}
// in your controller file
$user = User::find(5);
// a clean object that can be used anywhere
$user->next();
$user->previous();
In your App\Models\User.php
...
protected $appends = ['next', 'previous'];
public function getNextAttribute()
{
return $this->where('id', '>', $this->id)->orderBy('id','asc')->first();
}
public function getPreviousAttribute()
{
return $this->where('id', '<', $this->id)->orderBy('id','asc')->first();
}
In your Controller you can simply do this:
public function show(User $user)
{
return View::make('users.show')
->with('user', $user)
->with('previous', $user->previous)
->with('next', $user->next);
}
I understand the approach being taken here by user2581096 but I am not sure it is efficient (by any standards). We are calling the database 3 times for really no good reason. I suggest an alternative that will be way more efficient and scalable.
Do not pass the previous and next IDs to the view. This eliminates 2 unnecessary database calls.
Create the following routes:
users/{id}/next
users/{id}/previous
These routes should be used in the href attributes of the anchor tags
Add methods in the controller to handle each of the new routes you have created. For example:
public function getPrevious(){
// get previous user
$user = User::where('id', '<', $this->id)->orderBy('id','desc')->first();
return $this->show($user->id);
}
This function will only be called when you actually click on the button. Therefore, the database call is only made when you need to actually look up the user.
in-case you want to retrieve the prev/next records along with their data,
you can try
$id = 7; // for example
$prev = DB::table('posts')->where('id', '<', $id)->orderBy('id','desc')->limit(1);
$next = DB::table('posts')->where('id', '>', $id)->limit(1);
$res = DB::table('posts')
->where('id', '=', $id)
->unionAll($prev)
->unionAll($next)
->get();
// now $res is an array of 3 objects
// main, prev, next
dd($res);
1- the query builder is usually much faster than eloquent.
2- with union we are now only hitting the db once instead of 3.
To get next and previous post we can use max and min functions on Model id in laravel. here is an example to get this
https://usingphp.com/post/get-next-and-previous-post-link-in-laravel
The Controller:
public function post($id)
{
$post = Post::find($id);
$previous = Post::where('id', '<', $post->id)->max('id');
$next = Post::where('id', '>', $post->id)->min('id');
return view( 'post', compact( 'post', 'next', 'previous' ));
}
The View:
#if($next)
{{$next->title}}
#endif
#if($previous)
{{$previous->title}}
#endif
Here's a link I found that should help: http://maxoffsky.com/code-blog/laravel-quick-tip-get-previous-next-records/
It looks like for next you want to use: $next = User::where('id', '>', $id)->min('id'); and have the view as: Next
Also don't forget to pass $next to the view.
Simplest approach
// User.php
public static function findNext($id)
{
return static::where('id', '>', $id)->first();
}
// UserController.php
$nextUser = User::findNext($id);
// view
Next
Lazy approach :
// view
Next
// routes.php (should be optimized, this is just to show the idea)
Route::get('users/{user}/next', function($id) {
$nextUser = User::findNext($id);
return Redirect::to('user/' . $id);
});
// yourModel.php
public function previous()
{
return $this->find(--$this->id);
}
public function next()
{
return $this->find(++$this->id);
}
Works like magic, you can chain it:
$prevprev = Model::find($id)->previous()->previous();
$nextnext = Model::find($id)->next()->next();
First, get a record out of the database.
$post = Post::where('slug', $slug)->first();
With a database record, we can get the previous record where the record id is less than the id stored inside $post order by the id in descending order and use first() to get a single record back.
$previous = Post::where('id', '<', $post->id)->orderBy('id','desc')->first();
To get the next record it's almost the same query, this time get the record where the id is more than the id stored in $post.
$next = Post::where('id', '>', $post->id)->orderBy('id')->first();
Controller:
public function show($id)
{
// get the current user
$user = User::find($id);
// get previous user id
$previous = User::offset($user->id-2)->first();
// get next user id
$next = User::offset($user->id)->first();
return View::make('users.show')->with('previous', $previous)->with('next', $next);
}
i developed the code.
it work all times, even if we don't have any next or prev post
public function nextPost($table, $id)
{
$next = DB::table($table)->where('id', '>', $id)->orderBy('id','asc')->first();
if(!$next)
$next = DB::table($table)->orderBy('id','asc')->first();
return $next;
}
public function prevPost($table, $id)
{
$prev = DB::table($table)->where('id', '<', $id)->orderBy('id','desc')->first();
if(!$prev)
$prev = DB::table($table)->orderBy('id','desc')->first();
return $prev;
}