Passing Results from 2 Queries in a Single Route in Laravel 5 - laravel

I am trying to get posts from all users, plus tasks from only the current user. All passed into a single page with a single function and route. It returns an error page instead.
Controller
public function getDashboard()
{
$user = Auth::user();
$userId = $user->id;
$posts = Post::orderBy('created_at', 'desc')->get();
$tasks = Task::where('employee_id', $userId )->get();
return view('dashboard', compact('posts', 'tasks'));
}
Route
Route::get('/dashboard', [
'uses' => 'PostController#getDashboard',
'as' => 'dashboard',
])->middleware('auth');
Blade/View
<div>
#foreach($tasks as $task)
<p data-taskId="{{ $task->id }}">{{ $task->task_body }}</p>
#endforeach
</div>

Looks like possibly a syntax issue, as compact should work fine. Try this in your controller:
return view('dashboard', compact('posts', 'tasks'));
Then in your view, make sure to use the variables and not the class name, and as Karl Hill said, it's used within (), not {{}}:
#foreach($posts as $post)
{{$post->nameOrWhatever}}
#endforeach
#foreach($tasks as $task)
{{$task->nameOrWhatever}}
#endforeach

Related

Livewire Error: public property [message] must be of type: [numeric, string, array, null, or boolean]

I am getting this issue, and I don't understand what I am doing wrong as I did this same exact approach for another component on this site, and works perfectly....
ViewMessages.php
public $messages;
public function mount($messages)
{
$this->messages = $messages;
}
view-messages.blade.php
<div class="flex flex-col">
#foreach ($messages as $message)
{{$message->content}}
#endforeach
</div>
Everything works and it outputs all the messages correctly.
When I try and pass in a livewire component into the for each, it gives that error.
#foreach ($messages as $message)
#livewire('chat.show-message', ['message'=>$message], key('show-message-'.$message->id))
#endforeach
// ShowMessage.php
public $user;
public $message;
public $user_id;
public $content;
public function mount($message)
{
$this->message = $message;
}
Honestly am lost on what I am doing wrong, as I copied the exact same code and changed the variables that I used before. It works right now on the site when I do nested components.
<div class="flex flex-col space-y-4 py-4 overflow-y-auto">
#foreach ($chats as $chat)
#livewire('kanbans.show-sidebar-chat-message', ['chat'=>$chat], key('chat-'.$chat->id))
#endforeach
</div>
I redid this component already twice, and can't find any syntax issues or spelling errors. =/
The issue was with the DB Facade query
$messages = DB::select('SELECT * FROM chat_messages
WHERE (receiver_id = :auth_id and user_id = :user) OR (receiver_id = :user2 AND user_id = :auth_id2)',
['auth_id' => $auth_id, 'user' => $user->id, 'auth_id2' => $auth_id, 'user2' => $user->id]);
Although not sure yet how to pass in the $user->id but when I set the user id to #2, the livewire components work as intended.
public function view($user)
{
$user=User::where('id',$user)->firstOrFail();
$messages = ChatMessage::where(function ($query){
$query->where('user_id', '=', auth()->id() )
->where('receiver_id', '=', 2 );
})->orWhere(function ($query){
$query->where('user_id', '=', 2)
->where('receiver_id', '=', auth()->id() );
})->get();
return view('backend.chat.view-contact-chat',compact('user','messages'));
}

Weird Livewire + Turbolinks behavior

I'm building an admin panel in TALL (Laravel 7) + Turbolinks. One section only includes a Livewire component that shows a paginated table of Product elements and a search field (the only "strange" thing that I'm doing before this is injecting a Market model instance to the request in a middleware).
The problem arises when I go to /products route where is the livewire component included nothing works... The records of the first page are fine, but pagination links are dead and search field does nothing, no console errors, no livewire errors, it's like javascript is not working at all, and here's the strangest thing: if I reload the page, the Market data I loaded in middleware is added to the query string and everything starts working as intended.
Middleware:
public function handle($request, Closure $next) {
$market = Market::findOrFail(session('selected_market'));
$request->request->add(['market' => $market]);
return $next($request);
}
Livewire Component:
class ProductsTable extends Component{
use WithPagination;
public $search = '';
protected $queryString = [
'search' => ['except' => ''],
'page' => ['except' => 1],
];
public function render(){
$products = Product::where('market_id', request('market')->id)
->when($this->search !== '', function($query) {
$query->where('name', 'like', "%{$this->search}%");
$query->orWhere('brand', 'like', "%{$this->search}%");
})->paginate(15);
return view('livewire.products-table', ['products' => $products]);
}
}
Livewire Component View:
<input wire:model.debounce.500ms="search" type="search" name="search" id="search">
<table>
#forelse($products as $product)
<tr onclick="Turbolinks.visit('{{ route('product', $product->id) }}')">
<td>{{ $product->name }}</td>
...
</tr>
#empty
<tr><td>Nothing to show for {{ $search }}</td></tr>
#endforelse
</table>
{{ $products->links() }}
I'm really confused and tired with this, I have no clue what is going on and similar questions haven't been answered clearly.
Thanks
The solution was as simple as adding this to your scripts:
document.addEventListener("turbolinks:load", function(event) {
window.livewire.restart();
});

Missing required parameters for in a Update Form Laravel 5.2

I've been working on a webapp recently in laravel and i wanted to have a eddit function within tthe application. but im getting this error Missing required parameters for [Route: producten.update] [URI: producten/{producten}], and i dont know what i've done wrong.
This is the Routes im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'update', 'delete', 'edit', 'destroy', 'create']]);
This is the controller function im using for showing the edit page and updating.
The Edit function
public function edit(Request $request, Product $product)
{
// $product = Product::FindorFail($id);
// Product is a table with all products, with sellprice and buy price
// fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
The Update Function:
public function update(Request $request, Product $product)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
and this is the view i use for it.
{{Form::model($model, ['method' => 'PATCH', 'action' => 'ProductenController#update', $model ]) }}
{{ Form::label('naam:')}}
{{ Form::text('naam') }} <br>
{{ Form::label('inkoopPrijs:')}}
{{ Form::text('inkoopPrijs') }} <br>
{{ Form::label('verkoopPrijs:') }}
{{ Form::text('verkoopPrijs') }} <br>
{{Form::label('Fabrieken', 'Fabrieken Id:') }}
{{ Form::select('Fabrieken_Id', $fabrieks)}} <br>
{{ Form::submit('edit')}}
{{ Form::close() }}
if there is anything else that i need to add to the question just let me know and i'll add it
Missing thing is the id you are not getting id there in your edit function
your edit function should as i am assuming that you are just showing the form from this method where user can edit
public function edit($id)
{
$product = Product::FindorFail($id);
//Product is a table with all products, with sellprice and buy price
//fabriek = table that has a foreign key attached to the product table
return view('producten.edit', [
'model' => $product,
'fabrieks' => Fabriek::lists('Id')
]);
}
your update method should seem like this
public function update(Request $request, $id)
{
$product->update($request->all());
return redirect(Route('producten.index'));
}
your routes should like this no need for only
Route::resource('/producten', 'productionController');
edit route will be as
<a href="{{ route('production.edit', $model->id) }}">
Try this hope it will help

laravel 5.2 pagination pretty url

I am Using Laravel 5.2
Is There a Way To Get a Pagination Pretty URL in Laravel 5.2?
http://localhost:8000/backend/admin_user?page=10&page=1
And What I Would Like To Get,How generate Link Pretty Url:
http://localhost:8000/backend/admin_user/10/1
So you can try something like that:
Route::get('test/{page}', function ($page) {
return User::paginate(2, ['*'], 'page', $page);
});
You can achieve this with three simple steps.
Register the route:
Note the question mark, this makes the size and page values optional;
Route::get('backend/admin_user/{size?}/{page?}', ['uses' => 'BackendController#adminUser']);
Implement this function in your controller:
Note the default values, $size = 10, $page = 1. This makes sure that you don't get an error if you navigate to the url without the pagination.
<?php namespace App\Http\Controllers;
use App\Models\AdminUser;
use Illuminate\Pagination\LengthAwarePaginator;
class BackendController
{
public function adminUser($size = 10, $page = 1)
{
$collection = AdminUser::all();
$users = new LengthAwarePaginator($collection, $collection->count(), $size);
$users->resolveCurrentPage($page);
return view(backend.admin_user);
}
}
Use in your view like this:
<div class="container">
#foreach ($users as $user)
{{ $user->name }}
#endforeach
</div>
{{ $users->links() }}

Redirect back to same page (with variables) on form submit in Laravel 5

On my page events.index, I first display a list of events for the logged on user.
On my index page I have a form with option/select to let the user select and display the events of another user. When he submits that form, I would like my index function (controller) to use the $user_id value (from the form) and display the events.index page again, but for events of that selected user.
I'm not sure what would be the best approach:
Set a session variable to keep the user_id value? Not sure how to do that with a form.
Submit the form with a get method (and get an ugly ?user_id=1 URL)
Change my index route to accept the post method (although I already have that post/events route taken (by Route::post('events', 'EventsController#store'))
Not sure what would be a clean way to do this:
My route for events/index:
Route::get('events', [
'as' => 'event.index',
'uses' => 'EventsController#index'
]);
Events Controller
public function index()
{
// How to get the $user_id value from form?
if (empty($user_id))
{
$user_id = \Auth::user()->id;
}
$events = Event::where('events.user_id','=','$user_id');
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}
View for index
{!! Form::open(['route' => 'events.index', 'method' => 'get']) !!}
<select id="user_id" name="user_id">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
{!! Form::submit('Show events for this user') !!}
{!! Form::close() !!}
#foreach($events as $event)
...
#endforeach
You can get the user_id from a Request object, you just need to inject it in the index method:
public function index(Request $request)
{
$user_id = $request->get('user_id') ?: Auth::id();
$events = Event::where('events.user_id','=','$user_id')->get();
$users = User::all();
return view('events.index')->with(['events' => $events])->with(['users' => $users]);
}

Resources