I have 2 actions functions in my controller and I want to pass variable to an other action function
This is my first function in my controller
public function newUserAction(Request $request)
{ .........
$url = $this->generateUrl('userBundle_new_user_reasonCodeAjaxView',
array('id' => $newUser->getCode(),
'countCode' => $countCode,));
return $this->redirect($url);
This my second funtion in my controller
public function userCodeAjaxViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$pc = $em->getRepository('UserBundle:Code')->find($id);
if($pc != null)
{
return $this->render('UserBundle:userCodeView.html.twig', array(
'pc' => $pc,
));
}
And my twif looks like this
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ pc.name|trans }}
{{countCode}}
</div>
</fieldset>
</div>
</div>
</div>
I am getting an error Variable "countCode" does not exist in...
Is there any idea how I can use a variable from a controller in a other controller?
You can not get a variable from another controller.
Every request creates only one controller instance.
What you can do is create a Service that you can call in the controller.
Something like that:
class CountUserService{
public function count(){
return 1; // count users here
}
}
And the in the controller do this:
$service = new CountUserService();
$data=['countCode' => $service->count()];
return $this->render('UserBundle:userCodeView.html.twig', $data);
You are using the same template scope for the two controllers, and this is not possible. If you are using two controllers to render two simple informations, why not simply returning a JSON and displaying it in a more global template using AJAX ?
Else a pure symfony solution would be to have a main template view.html.twig where you would put
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ render(controller("AppBundle:UserController:newUserAction")) }}
{{ render(controller("AppBundle:UserController:userCodeAjaxViewAction")) }}
</div>
</fieldset>
</div>
</div>
Given that then your two controller action templates would be simple {{ pc.name|trans }} and {{countCode}}.
Hope it helps you out !
Related
`i am having a problem with my show.blade.php template, everything works fine but when I click on a post in the index page it directs me to the /post/1 page without showing the post content only the extended layout. please help
Web.php
Route:: resource('best-practices' , 'BestpracticesController');
*bestpracticescontroller.php
public function index()
{
$bestpractices = Bestpractices::all();
return view('bp.index',compact('bestpractices'));
}
public function show(Bestpractices $bestpractices)
{
return view('bp.show',compact('bestpractices'));
}
bp.show view template
#extends('layouts.front')
#section('content')
<div class="blog-details pt-95 pb-100">
<div class="container">
<div class="row">
<div class="col-12">
<div class="blog-details-info">
<div class="blog-meta">
<ul>
<li>{{$bestpractices->Date}}</li>
</ul>
</div>
<h3>{{$bestpractices->title}} </h3>
<img src="{{asset('storage/'.$bestpractices->cover_img)}}" alt="">
<div class="blog-feature">
{{$bestpractices->body}}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Thats because when you register routes via
Route::resource('best-parctices', BestparcticeController');
//Generated show route is equivalent to
Route::get(
'/best-practices/{best_practice}',
[BestpracticeController::class, 'show']
);
//route parameter is best_practice
Hence to achieve implicit route model binding the route parameter name must match the parameter name in the controller method
public function show(Bestpractices $bestpractices)
{
//here $bestpractices will be an int and not an object with
//model record as implicit route model binding doesn't work
return view('bp.show',compact('bestpractices'));
}
public function show(Bestpractices $best_practice)
{
//here implicit route model binding works so $best_practices is an object
//with model record
return view('bp.show',['bestpractices' => $best_practices]);
}
Or if you don't want to change the method parameter name in the controller methods then you need to override the route parameter name in the Route:resource() call when you define routes
Route::resource('best-practices', BestpracticesController::class)
->parameters([
'best-practices' => 'bestpractices'
]);
Laravel docs: https://laravel.com/docs/8.x/controllers#restful-naming-resource-route-parameters
I'm trying to pass anINT from this URL: myapp.build/courses/anINT (implemented in the CoursesController) to $id in the Lesson_unitsController function below. I've tried a lot of solutions, but I can't seem to get it right.
The function in the CoursesController which implements the url is:
public function show($id)
{
$course = Course::find($id);
return view('courses.show')->with('course', $course);
}
Part of the show.blade.php file is:
#if(!Auth::guest())
#if(Auth::user()->id == $course->user_id)
Edit Course
Lesson Units
{!!Form::open(['action'=> ['CoursesController#destroy', $course->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
The Lesson_unitsController functions are:
public function index()
{
$lesson_units = Lesson_unit::orderBy('title','asc')->paginate(10);
return view('lesson_units.index')->with('lesson_units', $lesson_units);
}
public function specificindex($id)
{
$course = Course::find($id);
return view('lesson_units.specificindex')->with('lesson_units', $course->lesson_units);
}
And the specificindex.blade.php file is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
Create lesson unit
<p>
<h3>Your lesson_units</h3>
#if(count($lesson_units) > 0)
<table class="table table-striped">
<tr><th>Title</th><th></th><th></th></tr>
#foreach($lesson_units as $lesson_unit)
<tr><td>{{$lesson_unit->title}}</td>
<td>Edit</td>
<td>
{!!Form::open(['action'=> ['Lesson_unitsController#destroy', $lesson_unit->id], 'method' => 'POST', 'class' => 'float-right'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
</td>
</tr>
#endforeach
</table>
#else
<p>You have no lesson unit.</p>
#endif
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in!
</div> </div> </div> </div> </div>
#endsection
The routes in web.php are:
Route::resource('courses', 'CoursesController');
Route::resource('lesson_units', 'Lesson_unitsController');
Route::get('/courses/{id}', 'Lesson_unitsController#specificIndex');
I want that when the link for Lesson Units is clicked on the page, the id in the url is passed to the specificindex function in the Lesson_unitsController. Now, I get just a blank page. What am I doing wrong?
Try to understand the concept of RESTful and CRUD.
By using Route::resource('courses', 'CoursesController');, Laravel has helped you to register the following routes:
Route::get('courses', 'CoursesController#index');
Route::get('courses/create', 'CoursesController#create');
Route::post('courses/{course}', 'CoursesController#store');
Route::get('courses/{course}/edit', 'CoursesController#edit');
Route::put('courses/{course}', 'CoursesController#update');
Route::delete('courses/{course}', 'CoursesController#destroy');
Then, when you make GET request to myapp.build/courses/123, Laravel will pass the request to the show function of your CoursesController like:
public function show(Course $course)
{
return view('lesson_units.index')->with('lesson_units', $course->lesson_units);
}
Laravel will automatically resolve the Course from your database using the parameter passed into the route myapp.build/courses/{course}.
Note: The variable name $course has to match with the one specify in route /{course}.
You don't have a route set up to handle the $id coming in. The resource method within the Route class will provide a GET route into your Lesson_unitsController controller without an expectation of any variable. It is the default index route, and by default doesn't pass a variable.
There are a couple of ways to do this, but the easiest is to just create a new route for your specific need:
Route::get('lesson_units/{id}', 'Lesson_unitsController#specificIndex');
And then make your specificIndex function in your controller with an incoming variable:
public function specialIndex($id)
{
$course = Course::find($id);
// return view to whatever you like
}
HTH
Is it possible to output to the same view from multiple controllers. I have one view called 'dashboard'. I have two variables: $users and $friends. I want to send data to these variables from different controllers. Do I need to add two controllers to the same route?
The view:
<div class="panel friendlist" id="friendlist">
<div class="panel-heading"><h3 class="panel-title">Result List</h3>
</div>
<div class="panel-body">
<ul class="list-group">
#foreach($friends as $friend)
<li class="list-group-item">{{ $friend->username }}
</li>
#endforeach
</ul>
</div>
</div>
</section>
<section class="row posts">
<div class="col-md-6 col-md-3-offset">
<header><h3>other posts</h3></header>
#foreach($posts as $post)
<article class="post">
<p>{{ $post->content }}</p>
<div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
The post controller:
public function getDashboard()
{
$posts = Post::orderBy('created_at','desc')->get();
return view('dashboard',['posts' => $posts]);
}
The friend controller:
public function getFriends()
{
$friends = Auth::user()->friends()->where('status','accepted')->get();
return view('dashboard',['friends' => $friends]);
}
Current route:
Route::get('/dashboard',[
'uses' => 'PostController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
#Amartya Barua, you can use view composer to share some variables to multiple views https://laravel.com/docs/5.8/views, Or you can create BaseService, and write reusable getters and inject BaseService to your controller, in this way you can able to access required getters to your Controller, if any question comment my answer
Simple thing you can do is
First create one Model and in this model create two functions for this two variable values.
In Controller where you want to use dashboard as view add model to your controller and simply pass call function of that model and pass this function values to view.
I'm trying to pass a variable from a controller route to a view so i can display data relating to new assoicate model. It's working for other contrllers, but i can't figure out why it's not here.
Controller
#Index - Not passing down
public function index(){
$Advert = new PropertyAdvert();
return view('pages/Advert/index', compact('Advert'));
}
#Show - Is working, this is just an example.
public function show($id){
$user = Auth::user();
$Advert = PropertyAdvert::where('id', $id)->first();
return view('pages/Advert/show', compact('Advert', 'user'));
}
This is the route
Route::get('/property', 'AdvertisementController#index');
Route::get('/advertise', 'AdvertisementController#create')->middleware('auth');
Route::post('/createadvert', 'AdvertisementController#store');
Route::get('/property/{id}', 'AdvertisementController#show');
This is the template i'm trying to pass down to show.blade.php
<div class="row text-center" style="display:flex; flex-wrap:wrap">
<div class="col-lg-12">
<h3>Our most recent properties</h3>
#foreach ($Advert as $property)
<div class="col-md-3 col-sm-6">
<div class="thumbnail">
<img src="data:image/gif;base64,{{ $property->photo }}">
<div class="caption">
<h4>{{$property->address .', '. $property->town .', '. $property->county}}</h4>
</div>
<p>
More Info!
</p>
</div>
</div>
#endforeach
</div>
</div>
</div>
Try this:
public function index(){
$Advert = PropertyAdvert::get();
return view('pages/Advert/index', compact('Advert'));
}
You need to actually access the data for that model.
I'm trying to make a posting system, with a resource routing combination on the posts. When I try to run the app to view the posts, it returns an error stating that the posts could not be found within the view. I have the controller code for the index and the show functions:
public function index()
{
$posts = Post::latest()->get();
return view('view', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
The view that I have for the app uses the post variable to display the posts:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<div class="panel panel-default">
<!-- Posts will be displayed on the same panel -->
<div class="panel-body" id="view">
#foreach($posts as $post)
<article id="post">
<a href="/view/posts{{ $post->id }}">
{{ $post->title }}
</a>
<div class="body">
{{ $post->body }}
</div>
<!-- Footer for posts will include interaction features -->
</article>
#endforeach
</div>
</div>
</div>
</div>
</div>
Is there something that the laravel installation isn't doing correctly? Is the compact function set up correctly?
Your controller index function should be something like this:
public function index()
{
$posts = Post::get();
return view('posts.index', compact('posts'));
}
The return of the index action is wrong
return view('view', compact('posts'));
Change 'view' with 'posts'
Use compact('posts')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.